Generate thumbnails with PHP by AR


/ Published in: PHP
Save to your folder(s)

* Creates thumbnail from image
* thumbnail dimensions can be set as parameters
* accepts JPG, JPEG, GIF, PNG
* preserves transparency for GIF and PNG on thumbnails
* call function like this: createthumb(images/original.jpg, thumbs/thumb.jpg, 80, 80);


Copy this code and paste it in your HTML
  1. /**
  2.   * Function that creates thumbnail from image
  3.   * Original author: Christian Heilmann
  4.   * Fixed and extended: Ales Rebec
  5.   *
  6.   * @param $name Original filename (fullpath to image)
  7.   * @param $filename Filename of the resized image (fullpath to thumbnail that will be created)
  8.   * @param $new_w width of resized image in px (ex. 80 or 100)
  9.   * @param $new_h height of resized image in px
  10.   */
  11. public function createthumb($name,$filename,$new_w,$new_h)
  12. {
  13. $type = 0;
  14. $size = getimagesize($name);
  15. $mime = $size['mime']; //get image mime type (ex. "image/jpeg" or "image/gif")
  16. $system=explode("/",$mime);
  17. if (preg_match("/jpg|jpeg/i",$system[sizeof($system)-1])) {$type=1; $src_img=imagecreatefromjpeg($name);}
  18. if (preg_match("/png/i",$system[sizeof($system)-1])) {$type=2; $src_img=imagecreatefrompng($name);}
  19. if (preg_match("/gif/i",$system[sizeof($system)-1])) {$type=3; $src_img=imagecreatefromgif($name);}
  20. $old_x=imageSX($src_img);
  21. $old_y=imageSY($src_img);
  22. if ($old_x > $old_y) //calculate thumnails dimenstions and preserve aspect ratio
  23. {
  24. $thumb_w=$new_w;
  25. $thumb_h=$old_y*($new_h/$old_x);
  26. }
  27. if ($old_x < $old_y)
  28. {
  29. $thumb_w=$old_x*($new_w/$old_y);
  30. $thumb_h=$new_h;
  31. }
  32. if ($old_x == $old_y)
  33. {
  34. $thumb_w=$new_w;
  35. $thumb_h=$new_h;
  36. }
  37. $dst_img= imagecreatetruecolor($thumb_w,$thumb_h); //create new image "canvas"
  38. if($type > 1) $this->setTransparency($dst_img, $src_img); //if GIF or PNG -> set tranparency
  39. imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
  40. if ($type == 3) imagegif($dst_img,$filename);
  41. else if ($type == 2) imagepng($dst_img,$filename);
  42. else imagejpeg($dst_img,$filename);
  43. imagedestroy($dst_img);
  44. imagedestroy($src_img);
  45. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.