使用动态尺寸创建透明 gif/png

Create transparent gif/png with dynamic dimensions

正在尝试创建具有用户定义尺寸的 gif 或 png。我得到的最接近的是这个:

$imgWidth = intval($_GET['x']);
$imgWidth = $imgWidth > 0 ? $imgWidth : 1;

$imgHeight = intval($_GET['y']);
$imgHeight = $imgHeight > 0 ? $imgHeight : 1;

$im = imagecreatetruecolor($imgWidth, $imgHeight);
$white = imagecolorallocate($im, 0, 0, 0);

imagecolortransparent($im, $white);

header('Content-Type: image/png');    
imagepng($im);
imagedestroy($im);

似乎 可以工作,但仔细检查它实际上创建了一个尺寸正确但前景为 0 x 0 像素的图像。这导致图像在某些客户端中显示不正确,例如我在 Photoshop 中遇到内存错误。我可以在 Fireworks 中打开它,但它在透明背景前的最左上角显示零像素位图:

我试过直接在imagecolortransparent($im, $white);后面加上imagefilledrectangle($im, 0, 0, $imgWidth, $imgHeight, $white);,但是没有效果。

我错过了什么?

这似乎是您提到的 Adob​​e 应用程序的一个特点。我没有这些的副本,所以我无法使用它们进行测试,但我尝试过的所有其他应用程序都会按预期呈现图像。

或许可以尝试以下方法,看看生成的图像是否更能被 Adob​​e 接受:

$imgWidth = intval($_GET['x']);
$imgWidth = $imgWidth > 0 ? $imgWidth : 1;

$imgHeight = intval($_GET['y']);
$imgHeight = $imgHeight > 0 ? $imgHeight : 1;

$im = imagecreatetruecolor($imgWidth, $imgHeight);
imagealphablending($im, false);
imagesavealpha($im, true);
$white = imagecolorallocatealpha($im, 255, 255, 255, 127); // fully transparent white.

imagefill($im, 0, 0, $white);

header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);

我猜测,问题的发生是因为您将透明度设置为 图像 的 属性 而不是 属性 颜色(或更准确地说,像素)。

前者通常用于基于调色板的图像 (imagecreate),其中像素要么完全不透明,要么完全透明,否则无法出现在图像中。也就是说,如果图像认为红色(ff0000)是完全透明的,那么所有个红色像素点都是透明的,根本不会显示颜色。

对于真彩色图像 (imagecreatetruecolor),将透明度指定为像素的 属性 是一种更好的方法,因为它可以实现部分透明度。这意味着您可以为不同的像素使用具有不同透明度级别的相同颜色。

上面的脚本使用了后一种方法。