使用gd库进行图片压缩

2019-07-15 11:11:57   php分享记录

 

使用gd库进行图片压缩

  1. public function compressedImage($imgsrc, $imgdst) {
  2. list($width, $height, $type) = getimagesize($imgsrc);
  3. $new_width = $width;//压缩后的图片宽
  4. $new_height = $height;//压缩后的图片高
  5. if($width >= 600){
  6. $per = 600 / $width;//计算比例
  7. $new_width = $width * $per;
  8. $new_height = $height * $per;
  9. }
  10. switch ($type) {
  11. case 1:
  12. $giftype = check_gifcartoon($imgsrc);
  13. if ($giftype) {
  14. $image_wp = imagecreatetruecolor($new_width, $new_height);
  15. $image = imagecreatefromgif($imgsrc);
  16. imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
  17. //90代表的是质量、压缩图片容量大小
  18. imagejpeg($image_wp, $imgdst, 90);
  19. imagedestroy($image_wp);
  20. imagedestroy($image);
  21. }
  22. ob_end_flush();
  23. break;
  24. case 2:
  25. $image_wp = imagecreatetruecolor($new_width, $new_height);
  26. $image = imagecreatefromjpeg($imgsrc);
  27. imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
  28. //90代表的是质量、压缩图片容量大小
  29. imagejpeg($image_wp, $imgdst, 90);
  30. imagedestroy($image_wp);
  31. imagedestroy($image);
  32. ob_end_flush();
  33. break;
  34. case 3:
  35. $image_wp = imagecreatetruecolor($new_width, $new_height);
  36. $image = imagecreatefrompng($imgsrc);
  37. imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
  38. //90代表的是质量、压缩图片容量大小
  39. imagejpeg($image_wp, $imgdst, 90);
  40. imagedestroy($image_wp);
  41. imagedestroy($image);
  42. break;
  43. }
  44. return $imgdst;
  45. }