更改图像背景

时间:2012-05-29 15:40:43

标签: php

现在我得到了带有白色背景的图片,但是想要将其更改为其他内容......

我尝试使用imagecolorset,索引为16777215(白色),但它不起作用D:

其他有此问题的人?甚至更好,知道如何解决它?

代码:

$img = imagecreatefrompng("http://chart.apis.google.com/chart?cht=qr&chs=300x300&chl=hellow"); 
$index = imagecolorat($img, 0, 0);
imagecolorset($img, $index, 0, 0, 255);
header("content-type:image/png");
imagepng($img);
imagedestroy($img);

1 个答案:

答案 0 :(得分:4)

似乎Google图表API正在创建Truecolor图像。注意:

[ghoti@pc ~]$ cat imgtest1.php 
<?php

$url = "http://chart.apis.google.com/chart?cht=qr&chs=300x300&chl=hello";
$img = imagecreatefrompng($url);

print "Colours before: " . imagecolorstotal($img) . "\n";
imagetruecolortopalette($img, FALSE, 2);
print "Colours after:  " . imagecolorstotal($img) . "\n";

[ghoti@pc ~]$ php imgtest1.php 
Colours before: 0
Colours after:  2
[ghoti@pc ~]$ 

因此,使用imagetruecolortopalette()转换为调色板图像似乎可以解决您的问题。

<?php

$url = "http://chart.apis.google.com/chart?cht=qr&chs=100x100&chl=hello";
$img = imagecreatefrompng($url);         # fetch the image
imagetruecolortopalette($img, FALSE, 2); # convert image from TC to palette
$bg = imagecolorat($img, 0, 0);          # get the bg colour's index in palette
imagecolorset($img, $bg, 0, 0, 255);     # make it blue

header("content-type:image/png");
imagepng($img);
imagedestroy($img);

结果:

enter image description here

相关问题