The clipping and zooming of php images produce the required thumbnails

  • 2020-05-27 04:29:18
  • OfStack

Picture is too large and specifications series 1, shows the control needs to be done by JavaScript, used in mobile devices is displayed when the result is bad and huge traffic, need to 1 times the existing image gallery images, generate conforms to the mobile devices use the thumbnail, the original client JS work transferred to server using PHP GD library to focus on.

Image source and required size:
$src_img = "wallpaper.jpg"; 
$dst_w = 300; 
$dst_h = 200; 

Clipping the image to maximize the display area and scaling to the specified size.

1. At the beginning, imagecopyresized method was used for image contour reduction. After the actual operation, it was found that the dryness was very serious after image reduction. Then I changed to imagecopyresampled (" 1 "here, a lot of this article has been reprinted on the Internet, but they all wrote imagecopyresampled as imagecopysampled, so they could not be used, so I reposted this method). This method will re-sample the image, and smooth the narrowed image, so as to greatly improve the clarity.
list($src_w,$src_h)=getimagesize($src_img); //  Gets the size of the original drawing  
$dst_scale = $dst_h/$dst_w; // Target image aspect ratio  
$src_scale = $src_h/$src_w; //  Aspect ratio of original drawing  
//  Too high  
$w = intval($src_w); 
$h = intval($dst_scale*$w); 
$x = 0; 
$y = ($src_h - $h)/3; 
//  Too wide  
$h = intval($src_h); 
$w = intval($h/$dst_scale); 
$x = ($src_w - $w)/2; 
$y = 0; 
//  clipping  
$croped=imagecreatetruecolor($w, $h); 
//  The zoom  
$scale = $dst_w/$w; 
$target = imagecreatetruecolor($dst_w, $dst_h); 
$final_w = intval($w*$scale); 
$final_h = intval($h*$scale); 
//  save  
$timestamp = time(); 
imagejpeg($target, "$timestamp.jpg"); 

Hopefully you can use it, it's a little bit more convenient.

Related articles: