Home  >  Article  >  Backend Development  >  PHP image cropping and thumbnail example

PHP image cropping and thumbnail example

WBOY
WBOYOriginal
2016-07-25 09:13:101019browse

In PHP programming, we often encounter situations where images are too large and have inconsistent specifications. The display control needs to be completed by JavaScript. When used on mobile devices, the display effect is not good and the traffic is huge. It requires the optimization of the existing image library. The image is processed once to generate thumbnails suitable for mobile devices, and the work originally done by the client-side JS is transferred to the server-side using PHP's GD library for centralized processing.

Requirements, image source and required size:

  1. list($src_w,$src_h)=getimagesize($src_img); //Get the original image size
  2. $dst_scale = $dst_h/$dst_w; //Target image aspect ratio
  3. $src_scale = $src_h/$src_w; // Original image aspect ratio
  4. if($src_scale>=$dst_scale)
  5. {
  6. // Too high
  7. $w = intval($src_w);
  8. $h = intval($ dst_scale*$w);
  9. $x = 0;
  10. $y = ($src_h - $h)/3;
  11. }
  12. else
  13. {
  14. // too wide
  15. $h = intval($src_h);
  16. $w = intval($h/$dst_scale);
  17. $x = ($src_w - $w)/2;
  18. $y = 0;
  19. }
  20. // Cropping
  21. $source=imagecreatefromjpeg($src_img);
  22. $croped= imagecreatetruecolor($w, $h);
  23. imagecopy($croped,$source,0,0,$x,$y,$src_w,$src_h);
  24. // Scale
  25. $scale = $dst_w/$w;
  26. $target = imagecreatetruecolor($dst_w, $dst_h);
  27. $final_w = intval($w*$scale);
  28. $final_h = intval($h*$scale);
  29. imagecopyresampled($target,$croped,0,0 ,0,0,$final_w,$final_h,$w,$h);
  30. // Save
  31. $timestamp = time();
  32. imagejpeg($target, "$timestamp.jpg");
  33. imagedestroy($target) ;
  34. ?>
Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn