PHP images are cropped and reduced to fit the needs of thumbnails _php instances
Source: Internet
Author: User
The picture is too big and the specification is not unified, the display control needs to rely on the JavaScript to complete, uses on the mobile device to display the result is not good and the traffic is huge, needs to carry on the processing to the existing picture library's picture, produces conforms to the mobile device the thumbnail image, The original client JS work to transfer to the server side with the PHP GD library to focus on processing.
picture source and desired size:
Copy CodeThe code is as follows:
$src _img = "wallpaper.jpg";
$DST _w = 300;
$DST _h = 200;
Trims the image to ensure that the image area is maximized and scaled to the specified size.
At first, the Imagecopyresized method was used to reduce the image, and the actual operation revealed that the dryness point was very serious after the image was reduced. And then swap with imagecopyresampled (here to say, the online reprint of this article a lot, but they all put imagecopyresampled written imagecopysampled cause can't use, so I just re-paste this) method, This method will resample the image and smooth the zoomed image, so that the sharpness can be greatly improved.
Copy CodeThe code is as follows:
List ($src _w, $src _h) =getimagesize ($src _img); Get the original size
$DST _scale = $dst _h/$dst _w; Target image aspect ratio
$src _scale = $src _h/$src _w; Original aspect ratio
if ($src _scale>= $dst _scale)
{
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;
}
Cutting
$source =imagecreatefromjpeg ($src _img);
$croped =imagecreatetruecolor ($w, $h);
Imagecopy ($croped, $source, 0,0, $x, $y, $src _w, $src _h);
Scaling
$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);
?>
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.