Home >Backend Development >PHP Tutorial > 解决PHP剪切缩略图生成png,gif透明图时,黑色背景有关问题

解决PHP剪切缩略图生成png,gif透明图时,黑色背景有关问题

WBOY
WBOYOriginal
2016-06-13 12:48:25942browse

解决PHP剪切缩略图生成png,gif透明图时,黑色背景问题

最近做头像上传用到剪切,只要GIF或者PNG是透明的话,剪切后都会变成黑色的背景图。

?

解决方案有2种:

?

1.背景图填充白色的背景。

?

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

?

2.设置图片走透明通道。

?

$img = imagecreatefrompng($src);
imagesavealpha($img,true);//这里很重要;
$thumb = imagecreatetruecolor(300,300);
imagealphablending($thumb,false);//这里很重要,意思是不合并颜色,直接用$img图像颜色替换,包括透明色;
imagesavealpha($thumb,true);//这里很重要,意思是不要丢了$thumb图像的透明色;
imagecopyresampled($thumb,$img,0,0,0,0,300,300,300,300);
imagepng($thumb,"temp.png");

?

以上2种方式均测试成功。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn