Posted By

cerxx on 11/22/18


Tagged

php-hacks


Versions (?)

Optimize downloaded images using php (jpeg)


 / Published in: PHP
 

URL: http://qaru.site/questions/406415/optimize-uploaded-images-with-php-jpeg#1832451

The imagejpeg function is where you assign quality. If you already set this value to the appropriate value, you can do some more.

The page speed probably thinks that all images above a certain size "need to be compressed," perhaps simply guaranteeing that they are all as small as reasonable (in terms of height / width) and compressed.

  1. function compressImage($source_url, $destination_url, $quality) {
  2.  
  3. //$quality :: 0 - 100
  4.  
  5. if( $destination_url == NULL || $destination_url == "" ) $destination_url = $source_url;
  6.  
  7. $info = getimagesize($source_url);
  8.  
  9. if ($info['mime'] == 'image/jpeg' || $info['mime'] == 'image/jpg')
  10. {
  11. $image = imagecreatefromjpeg($source_url);
  12. //save file
  13. //ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default is the default IJG quality value (about 75).
  14. imagejpeg($image, $destination_url, $quality);
  15.  
  16. //Free up memory
  17. imagedestroy($image);
  18. }
  19. elseif ($info['mime'] == 'image/png')
  20. {
  21. $image = imagecreatefrompng($source_url);
  22.  
  23. imageAlphaBlending($image, true);
  24. imageSaveAlpha($image, true);
  25.  
  26. /* chang to png quality */
  27. $png_quality = 9 - round(($quality / 100 ) * 9 );
  28. imagePng($image, $destination_url, $png_quality);//Compression level: from 0 (no compression) to 9(full compression).
  29. //Free up memory
  30. imagedestroy($image);
  31. }else
  32. return FALSE;
  33.  
  34. return $destination_url;
  35.  
  36. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: roseepeter on November 29, 2018

Need help I have to optimize .jpeg images using PHP actually I have to make a website for MasterPaperWriters.com - Master Paper Writers and facing some problems can you help me?

You need to login to post a comment.