Solve the problem of black background when generating png images by cropping thumbnails in PHP. when a gif image is transparent, the image is cut recently. as long as the GIF or PNG image is transparent, it will become a black background image after cutting .? There are two solutions :? 1. fill the background image with a white background .? $ White = imagecolorallocate ($ dstim, 255,255, solves the black background problem when generating png and gif transparent images by cropping thumbnails in PHP.
Recently, you have used cropping to upload an avatar. as long as the GIF or PNG image is transparent, the cropped image will become a black background image.
?
There are two solutions:
?
1. fill the background image with a white background.
?
$ White = imagecolorallocate ($ dstim, 255,255,255); imagefilledrectangle ($ dstim, 0,0, $ width, $ height, $ white); imagecolortransparent ($ dstim, $ white );
?
2. set the image to a transparent channel.
?
$ Img = imagecreatefrompng ($ src); imagesavealpha ($ img, true); // important here; $ thumb = imagecreatetruecolor (300,300); imagealphablending ($ thumb, false ); // This is very important. it means that the $ img Image color is replaced directly without merging colors, including transparent colors; imagesavealpha ($ thumb, true); // It is very important here, do not lose the transparent color of $ thumb image; imagecopyresampled ($ thumb, $ img, 300,300,300,300,); imagepng ($ thumb, "temp.png ");
?
Both methods are successfully tested.