Solve the problem of black background when PHP cuts thumbnails to generate png, gif transparent images

Recently, I used cutting for avatar upload. As long as the GIF or PNG is transparent, it will become a black background image after cutting.

 

There are 2 solutions:

 

1. The background image fills the white background.

 

$white = imagecolorallocate($dstim,255,255,255);
imagefilledrectangle($dstim,0,0,$width,$height,$white);
imagecolortransparent($dstim,$white);

 

2. Set the picture to go through the transparent channel.

 

$img = imagecreatefrompng($src);
imagesavealpha($img,true);//This is very important;
$thumb = imagecreatetruecolor(300,300);
imagealphablending($thumb, false);//This is very important, which means that the color is not merged, and it is directly replaced with the color of the $img image, including the transparent color;
imagesavealpha($thumb, true);//This is very important, meaning don't lose the transparent color of the $thumb image;
imagecopyresampled($thumb,$img,0,0,0,0,300,300,300,300);
imagepng($thumb,"temp.png");

 

Both of the above methods were tested successfully.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327051705&siteId=291194637