Crop and scale PHP Images

Source: Internet
Author: User

The image size is too large and its specifications are not uniform. The display control needs to be completed by JavaScript. When used on mobile devices, the display effect is poor and the traffic is huge. You need to process the image of the existing image library once, generate thumbnails that meet the requirements of mobile devices, and transfer the work done by the original client JS to the server using the php gd library for centralized processing.

Image Source and required size:

$src_img = "wallpaper.jpg";$dst_w = 300;$dst_h = 200;

Crop the image to maximize the display of the image area and scale proportionally to the specified size.

At first, the imagecopyresized method was used for image proportional reduction. After the actual operation, it was found that the dry points were very serious after the image was reduced. Then use the imagecopysampled method. This method will re-sample the image and perform smooth processing on the reduced image to greatly improve the definition.

<? Phplist ($ src_w, $ src_h) = getimagesize ($ src_img); // obtain the source image size $ dst_scale = $ dst_h/$ dst_w; // target image Aspect Ratio $ src_scale = $ src_h/$ src_w; // source 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;} // crop $ 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 ); imagecopysampled ($ target, $ croped, 0, 0, 0, $ final_w, $ final_h, $ w, $ h); // save $ timestamp = time (); imagejpeg ($ target, "condition"); imagedestroy ($ target);?>

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.