[英]Colorize PNG using PHP GD
I want to colorize some PNGs using PHP GD.我想使用 PHP GD 为一些 PNG 着色。 For testing purpose i hardcoded the color red (255,0,0) which later will be replace by a dynamic variable.
出于测试目的,我对红色 (255,0,0) 进行了硬编码,稍后将替换为动态变量。
For example i have these two images:例如我有这两个图像:
Image 1:图 1:
Image 2:图 2:
Using my code, only image 2 works as it should.使用我的代码,只有图像 2 可以正常工作。
The dog image however has some sort of gray box, don't know where the heck this comes from.然而,狗图像有某种灰色框,不知道这是从哪里来的。
Here is the code I'm using:这是我正在使用的代码:
<?php
$im = imagecreatefrompng('dog.png');
imagealphablending($im, false);
imagesavealpha($im, true);
$w = imagesx($im);
$h = imagesy($im);
for ($x = 0; $x < $w; $x++) {
for ($y = 0; $y < $h; $y++) {
$color = imagecolorsforindex($im, imagecolorat($im, $x, $y));
$r = ($color['red'] * 255) / 255;
$g = ($color['green'] * 0) / 255;
$b = ($color['blue'] * 0) / 255;
imagesetpixel($im, $x, $y, imagecolorallocatealpha($im, $r, $g, $b, $color['alpha']));
}
}
imagepng($im, 'result.png');
imagedestroy($im);
Why does it work with image 2 but not image 1?为什么它适用于图像 2 而不适用于图像 1? I only can think of some sort of alpha mask going on with image 1.
我只能想到图像 1 上的某种 alpha 蒙版。
Hope somebody can help me希望有人可以帮助我
It's not mentioned in the documentation for imagecolorallocate()
or its alpha equivalent, but someone has pointed out in the comments that you can only allocate 255 colours in the image before running out.在
imagecolorallocate()
或其 alpha 等价物的文档中imagecolorallocate()
提到它,但有人在评论中指出, 在用完之前,您只能在图像中分配 255 种颜色。 Check that the allocation hasn't failed before using the new colour.在使用新颜色之前检查分配没有失败。 If it has, use
imagecolorclosestalpha()
to get the next best thing.如果有,请使用
imagecolorclosestalpha()
来获得下一个最好的结果。
<?php
$replace = [255, 0, 0];
array_walk($replace, function(&$v, $k) {$v /= 255;});
$im = imagecreatefrompng('dog.png');
for ($x = 0; $x < imagesx($im); $x++) {
for ($y = 0; $y < imagesy($im); $y++) {
$color = imagecolorsforindex($im, imagecolorat($im, $x, $y));
$r = $color["red"] * $replace[0];
$g = $color["green"] * $replace[1];
$b = $color["blue"] * $replace[2];
$a = $color["alpha"];
$newcolour = imagecolorallocatealpha($im, $r, $g, $b, $a);
if ($newcolour === false) {
$newcolour = imagecolorclosestalpha($im, $r, $g, $b, $a);
}
imagesetpixel($im, $x, $y, $newcolour);
}
}
imagepng($im, 'result.png');
imagedestroy($im);
I'v got it working using my code.我已经使用我的代码让它工作了。 All i had to do is add
imagepalettetotruecolor($im);
我所要做的就是添加
imagepalettetotruecolor($im);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.