GIF 透明背景变为黑色


GIF transparent background turned to black

我有一个脚本可以调整上传图像的大小。它适用于 PNG 和 JPG,但对于 GIF,它会将调整大小的 GIF 中的透明度渲染为黑色。

    $src = imagecreatefromgif($file);
    $dst = imagecreatetruecolor($newWidth, $newHeight);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); 
    imagegif($dst, $file);

从手册页 http://us3.php.net/manual/en/function.imagecopyresampled.php#104028

imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127));
imagealphablending($new, false);
imagesavealpha($new, true);

被一张海报用来保持透明度。

这里有一个提示...始终查看用户对 php.net 的评论,因为它们通常非常有助于理解函数的细微差别并提供处理常见任务的提示。

我假设这会转到一个网页,如果确实如此,您可以输出具有正确属性的图像标签?

echo "<img src='$file' width='$newWidth' height='$newHeight' />";

您仍然需要在新图像中设置透明度。以下内容摘自 php 文档:

<?php
// Create a 55x30 image
$im = imagecreatetruecolor(55, 30);
$red = imagecolorallocate($im, 255, 0, 0);
$black = imagecolorallocate($im, 0, 0, 0);
// Make the background transparent
imagecolortransparent($im, $black);
// ^^ This is the command you are missing.
// Draw a red rectangle
imagefilledrectangle($im, 4, 4, 50, 25, $red);
// Save the image
imagepng($im, './imagecolortransparent.png');
imagedestroy($im);
?>

在您的情况下,您希望使透明度与原始透明度的颜色相同 - 我总是制作一个可怕的紫色或会a)在我的图像处理软件中像拇指酸痛一样突出的东西,其次,有一个RGB键几乎不可能错误地包含在图像中。