浅谈关于PHP解决图片无损压缩的问题

  1. header("Content-type: image/jpeg");
  2. $file = "111.jpg";
  3. $percent = 1.5; //图片压缩比
  4. list($width, $height) = getimagesize($file); //获取原图尺寸
  5. //缩放尺寸
  6. $newwidth = $width * $percent;
  7. $newheight = $height * $percent;
  8. $src_im = imagecreatefromjpeg($file);
  9. $dst_im = imagecreatetruecolor($newwidth, $newheight);
  10. imagecopyresized($dst_im, $src_im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
  11. imagejpeg($dst_im); //输出压缩后的图片
  12. imagedestroy($dst_im);
  13. imagedestroy($src_im);

我发现用php的imagecopyresized把大图片缩成小图片时,图片会变得很模糊,这时候要提升清晰度不如用 imagecopyresampled 代替 imagecopyresized也许会更好。

注:压缩有损失是必然的,看的清楚与否实际上就是是否接受这个范围的问题.比如你图像上原图有些点是2px,但是你压缩5倍,那么这些点就会消失。

  1. <?php
  2. /**
  3. * desription 压缩图片
  4. * @param sting $imgsrc 图片路径
  5. * @param string $imgdst 压缩后保存路径
  6. */
  7. function image_png_size_add($imgsrc,$imgdst){
  8. list($width,$height,$type)=getimagesize($imgsrc);
  9. $new_width = ($width>600?600:$width)*0.9;
  10. $new_height =($height>600?600:$height)*0.9;
  11. switch($type){
  12. case 1:
  13. $giftype=check_gifcartoon($imgsrc);
  14. if($giftype){
  15. header('Content-Type:image/gif');
  16. $image_wp=imagecreatetruecolor($new_width, $new_height);
  17. $image = imagecreatefromgif($imgsrc);
  18. imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
  19. imagejpeg($image_wp, $imgdst,75);
  20. imagedestroy($image_wp);
  21. }
  22. break;
  23. case 2:
  24. header('Content-Type:image/jpeg');
  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. imagejpeg($image_wp, $imgdst,75);
  29. imagedestroy($image_wp);
  30. break;
  31. case 3:
  32. header('Content-Type:image/png');
  33. $image_wp=imagecreatetruecolor($new_width, $new_height);
  34. $image = imagecreatefrompng($imgsrc);
  35. imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
  36. imagejpeg($image_wp, $imgdst,75);
  37. imagedestroy($image_wp);
  38. break;
  39. }
  40. }
  41. /**
  42. * desription 判断是否gif动画
  43. * @param sting $image_file图片路径
  44. * @return boolean t 是 f 否
  45. */
  46. function check_gifcartoon($image_file){
  47. $fp = fopen($image_file,'rb');
  48. $image_head = fread($fp,1024);
  49. fclose($fp); //phpfensi.com
  50. return preg_match("/".chr(0x21).chr(0xff).chr(0x0b).'NETSCAPE2.0'."/",$image_head)?false:true;
  51. }
  52. ?>