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:
-
- list($src_w,$src_h)=getimagesize($src_img); //Get the original image size
- $dst_scale = $dst_h/$dst_w; //Target image aspect ratio
- $src_scale = $src_h/$src_w; // Original image aspect ratio
- if($src_scale>=$dst_scale)
- {
- // Too high
- $w = intval($src_w);
- $h = intval($ dst_scale*$w);
- $x = 0;
- $y = ($src_h - $h)/3;
- }
- else
- {
- // too wide
- $h = intval($src_h);
- $w = intval($h/$dst_scale);
- $x = ($src_w - $w)/2;
- $y = 0;
- }
- // Cropping
- $source=imagecreatefromjpeg($src_img);
- $croped= imagecreatetruecolor($w, $h);
- imagecopy($croped,$source,0,0,$x,$y,$src_w,$src_h);
- // Scale
- $scale = $dst_w/$w;
- $target = imagecreatetruecolor($dst_w, $dst_h);
- $final_w = intval($w*$scale);
- $final_h = intval($h*$scale);
- imagecopyresampled($target,$croped,0,0 ,0,0,$final_w,$final_h,$w,$h);
- // Save
- $timestamp = time();
- imagejpeg($target, "$timestamp.jpg");
- imagedestroy($target) ;
- ?>
Copy code
|