Use PHP to generate PNG thumbnails for transparent background sharing and png thumbnails.
Previously, 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 a PNG thumbnail is generated, 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 with www.chhua.com */function pngthumb ($ sourePic, $ smallFileName, $ width, $ heigh) {$ image = imagecreatefrompng ($ sourePic); // PNG imagesavealpha ($ 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 heavy here Yes, it means that the color is not merged, and $ img image color is replaced directly, including transparent color; imagesavealpha ($ thumb, true); // It is important here, do not lose the transparent color of $ thumb image; if (imagecopyresampled ($ thumb, $ image, $ width, $ heigh, $ BigWidth, $ BigHeigh )) {imagepng ($ thumb, $ smallFileName);} return $ smallFileName; // return the thumbnail path, indicating www.chhua.com} pngthumb ("a.png", "c.png", 300,300 ); // call?>
How transparent is the background for generating PNG thumbnails? -PHP advanced Discussion
Use PHOTOSHOP to extract the desired image and copy a layer. Then delete the background layer and save it as PNG.
Using the following php thumbnails function, you cannot generate thumbnails for some JPG images, but others can. Why?
Note:
1: The image should be prepared for output or storage after being determined, and then the imagecreatefromjpeg method should be used.
2: imagesy ($ src_img); Consider using list ($ width, $ height) = getimagesize ($ src_img );
3: $ ratio_h = 1.0 * $ new_height/$ h; // n = unknown. If 1 is multiplied by any n, the result is still n. Why?
4: Your program receives the size of external input, which leads to distortion and deformation of the output or saved image.
5: $ ratio = 1.0;
If ($ ratio_w <= 1 & $ ratio_h <= 1 ){
If ($ ratio_w <$ ratio_h) {} else {} // NOTE 4: Use the ternary Algorithm
6: $ inter_h = (int) ($ new_height/$ ratio); // PHP is not as sensitive to data types as Java and does not need to use int for forced conversion.
7: after processing, remember to destroy the image imagedestroy ();
Finally, you can explain the effect you want.