Jump to content

Creating Thumbnails for jpg, gif, png?


glassfish

Recommended Posts

The tutorials you're have found most likely uses the GD image extension for creating the thumbnails.

 

In that case all you need to do is swap out the jpeg functions to the gif or png equivalent

 

Such as change imagecreatefromjpeg and imagejpeg functions to

Here I found this script:

function make_thumb($src, $dest, $desired_width) {

	/* read the source image */
	$source_image = imagecreatefromjpeg($src);
	$width = imagesx($source_image);
	$height = imagesy($source_image);
	
	/* find the "desired height" of this thumbnail, relative to the desired width  */
	$desired_height = floor($height * ($desired_width / $width));
	
	/* create a new, "virtual" image */
	$virtual_image = imagecreatetruecolor($desired_width, $desired_height);
	
	/* copy source image at a resized size */
	imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
	
	/* create the physical thumbnail image to its destination */
	imagejpeg($virtual_image, $dest);
}

I found it at: http://davidwalsh.name/create-image-thumbnail-php

 

 

Can this script be modified so all three file extensions can be used?

 

Or I could be using this script three times? I will try that in a minute.

 

Thanks for the answer so far.

You'd make a separate function which will determine which image functions to use depending on the image extension.

 

Example (untest code).

function getImageFunctionsByExtension($src)
{
    $extension = pathinfo($src, PATHINFO_EXTENSION);

    switch($extension)
    {
       case 'gif':
          $functions = array('imagecreatefromgif', 'imagegif');   // list of gif function names
       break;

       case 'png':
          $functions = array('imagecreatefrompng', 'imagepng');   // list of png function names
       break;

       case 'jpg':
       case 'jpeg':
          $functions = array('imagecreatefromjpeg', 'imagejpeg'); // list of jpeg function names
       break;
    }

    return $functions;
}

Now replace    $source_image = imagecreatefromjpeg($src);     with

list($imagecreatefromfunc, $imagefunc)  = getImageFunctionsByExtension($src);

$source_image = $imagecreatefromfunc($src);

And then replace   imagejpeg($virtual_image, $dest);   with    $imagefunc($virtual_image, $dest);

 

The code will now use the correct image functions based on the extension of the image.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.