使用PHP和gdlib将颜色变为透明

时间:2012-09-02 12:51:29

标签: php transparency transparent alpha gdlib

我尝试使用php gdlib在现有图像中将灰色(rgb:235,235,240)变为透明。

这是我使用的代码:

<?php
header("Content-type:image/png");
$picture = imagecreatefrompng("test.png");
$grey = imagecolorallocate($picture, 235, 235, 240);
imagecolortransparent($picture, $grey);
imagepng($picture);
imagedestroy($picture, "newpicture.png");
?>

当test.png上有很多不同的颜色时,此代码将无效。否则,当test.png上只有少量颜色时,此代码可以正常工作。为什么呢?

1 个答案:

答案 0 :(得分:2)

它不起作用,因为您没有将修改后的图片保存到磁盘 您当前的代码:

imagepng($picture);

会将修改过的图片发送到浏览器,但您也在输出HTML代码:

<img src="mytest.png" />

以这种方式修改代码:

imagepng($picture, 'mytest.png'); // save the picture to disk

然后,您的HTML代码将显示已修改的图片。

查看文档:{​​{3}}

您必须使用此行将灰色存储到$grey

$grey = imagecolorallocate($picture, 235, 235, 240);

imagepng完全不同。