[英]Colorize PNG using PHP GD
我想使用 PHP GD 為一些 PNG 着色。 出於測試目的,我對紅色 (255,0,0) 進行了硬編碼,稍后將替換為動態變量。
例如我有這兩個圖像:
圖 1:
圖 2:
使用我的代碼,只有圖像 2 可以正常工作。
然而,狗圖像有某種灰色框,不知道這是從哪里來的。
這是我正在使用的代碼:
<?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);
為什么它適用於圖像 2 而不適用於圖像 1? 我只能想到圖像 1 上的某種 alpha 蒙版。
希望有人可以幫助我
在imagecolorallocate()
或其 alpha 等價物的文檔中imagecolorallocate()
提到它,但有人在評論中指出, 在用完之前,您只能在圖像中分配 255 種顏色。 在使用新顏色之前檢查分配沒有失敗。 如果有,請使用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);
我已經使用我的代碼讓它工作了。 我所要做的就是添加imagepalettetotruecolor($im);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.