PHP 调整图像大小并保存透明 PNG

标签 php png transparent

我的网站中有一个 png 图像上传脚本,我正在将大图像缩小为小尺寸,并且我正在使用此代码,但它丢失了透明背景

$image = $tmp; // Uploaded Image
$maxImgWidth = 224;
$src = imagecreatefrompng($image);
list($width, $height) = getimagesize($image);
$newwidth = $maxImgWidth;
$newheight = ($height / $width) * $newwidth;
$newImage = imagecreatetruecolor($newwidth, $newheight);
imagealphablending($image, true);
imagesavealpha($image, true);
imagecopyresampled($newImage, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagepng($newImage, "../thumb/$name_after-$code.$ext", 1);
imagedestroy($src);
imagedestroy($newImage);

此代码使图像不透明:

enter image description here

我想要像这样的透明背景:

enter image description here

最佳答案

抱歉,我没有 PHP 经验,但在我阅读 this page 后,我认为您可能需要在设置保存阿尔法为真

后添加透明颜色
imagesavealpha($image, true);
$color = imagecolorallocatealpha($image, 0, 0, 0, 127);
imagefill($image, 0, 0, $color);

如果仍然无法尝试imagecolorallocatealpha()之后添加此内容,

imagecolortransparent($image, $color); 

关于PHP 调整图像大小并保存透明 PNG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22316475/

相关文章:

php - 哪个是首选,关联数组还是对象?

php - 使用 meekro 库对可用库存数量求和

ios6 - 存档应用内购买将png检测为iOS6上的可执行文件

C# MonoGame 帮助? (Content.Load<Texture2D> ("Invader");)

image - 如何将透明图像添加到 MS Access 2010 按钮控件?

php - 从结果中删除 0

PHP - 从对象数组中删除重复项

image - 你更喜欢哪个?用于图形和图表的 SVG、HTML5 或 regen'd-PNG?

css - 将 div 堆叠在一起

python - 如何在使用 cv2 保持透明度的同时将图像转换为灰度?