Use PHP to generate PNG thumbnails with transparent backgrounds

Source: Internet
Author: User
Tags transparent color
This article mainly introduces the PNG thumbnail function sharing for PHP to generate a transparent background. For more information, see

This article mainly introduces the PNG thumbnail function sharing for PHP to generate a transparent background. For more information, see

I wrote a function for generating thumbnails in PHP in my WEB development notes. Although this function can generate thumbnails, it has some drawbacks. When generating PNG thumbnails, the background is black ,, today I wrote another function to make up for it. The code is very simple, that is, imagealphablending ($ thumb, false); and imagesavealpha ($ thumb, true); it is very important to save the alpha value of PNG and do not lose it.

The function is as follows:

<? PHP/** $ sourePic: source image path * $ smallFileName: thumbnail name * $ width: thumbnail width * $ heigh: thumbnail height * reprinted and noted */function pngthumb ($ sourePic, $ smallFileName, $ width, $ heigh) {$ image = imagecreatefrompng ($ sourePic); // PNGimagesavealpha ($ image, true ); // It is very important that you do not lose the transparent color of $ sourePic images; $ BigWidth = imagesx ($ image); // The width of the larger image $ BigHeigh = imagesy ($ image ); // large Image Height $ thumb = imagecreatetruecolor ($ width, $ heigh); imagealphablending ($ thumb, false); // It is very important here, meaning that the color is not merged and $ Img image color replacement, including transparent color; imagesavealpha ($ thumb, true); // This is important, meaning do not lose the transparent color of $ thumb image; if (imagecopyresampled ($ thumb, $ image, 0, 0, 0, $ width, $ heigh, $ BigWidth, $ BigHeigh) {imagepng ($ thumb, $ smallFileName);} return $ smallFileName; // return to the thumbnail path for Reprinted note} pngthumb ("a.png", "c.png", 300,300); // call?>

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.