Saturday, March 10, 2012

PHP, create a thumb image


In PHP, you may need to create a thumb image from an existing  image.  This is widely used in PHP photo album creation. Below is the explanation of how to create a thumb image from existing image in PHP.

1) First we need to use PHP getimagesize function  to get the image type.
See below for the function getimagesize return vales:
list($width$height$type$attr) = getimagesize("img/flag.jpg");
The third element of  getimagesize() return the image type. You can use 
print_r(get_defined_constants());
to get the image type.
[IMAGETYPE_GIF] => 1
[IMAGETYPE_JPEG] => 2
[IMAGETYPE_PNG] => 3
[IMAGETYPE_SWF] => 4
[IMAGETYPE_PSD] => 5
[IMAGETYPE_BMP] => 6
[IMAGETYPE_TIFF_II] => 7
[IMAGETYPE_TIFF_MM] => 8
[IMAGETYPE_JPC] => 9
[IMAGETYPE_JP2] => 10
[IMAGETYPE_JPX] => 11
[IMAGETYPE_JB2] => 12
[IMAGETYPE_SWC] => 13
[IMAGETYPE_IFF] => 14
[IMAGETYPE_WBMP] => 15
[IMAGETYPE_JPEG2000] => 9
[IMAGETYPE_XBM] => 16
[IMAGETYPE_ICO] => 17
[IMAGETYPE_UNKNOWN] => 0
[IMAGETYPE_COUNT] => 18


2) Then you can use  PHP built in function imagecreatetruecolor()  to create an 
image identifier representing a black image of the specified size.

3) And  use PHP built in function imagecopyresized() to copy a image and resize it.

4) And  you  can use PHP function imagejpeg() to create a JPEG file from the
 given image. similar function: 
  
Example of function  imagejpeg:
<?php 
// Create a blank image and add some text
 $im imagecreatetruecolor(12020);
 $text_color imagecolorallocate($im2331491);
 imagestring($im155,  'A Simple Text String'$text_color);// Save the image as 'simpletext.jpg' 
imagejpeg($im'simpletext.jpg');// Free up memoryimagedestroy($im);
 ?>
 
5) Finally, below is the  PHP function code to make thumb jpeg file from 
a source image of format gif, jpeg or png:

function create_thumb($srcfile,$dest,$desired_width)
{

  /* read the source image */
 $x = @getimagesize($srcfile); 
  switch($x[2]) { 
   case 1: 
        $source_image = imagecreatefromgif($srcfile); 
       break; 
   case 2: 
        $source_image = imagecreatefromjpeg($srcfile);
       break; 
   case 3: 
        $source_image = imagecreatefrompng($srcfile);  
       break; 
   default: 
        echo "file is not a valid image file.<br>"; 
       break;
  } 
  $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 */ 
imagecopyresized($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);
}

No comments:

Post a Comment