用PHP通过AR生成缩略图

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用PHP通过AR生成缩略图相关的知识,希望对你有一定的参考价值。

* 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);
  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. }

以上是关于用PHP通过AR生成缩略图的主要内容,如果未能解决你的问题,请参考以下文章

php用一个函数生成缩略图

php用一个函数生成缩略图

PHP PHP代码生成当前目录中所有图像的缩略图

PHP图片生成缩略图

PHP生成缩略图--等比缩略图

PHP生成缩略图--封装类