【问题标题】:Colorize PNG using PHP GD使用 PHP GD 为 PNG 着色
【发布时间】:2019-06-27 21:27:57
【问题描述】:

我想使用 PHP GD 为一些 PNG 着色。出于测试目的,我硬编码了红色 (255,0,0),稍后将被动态变量替换。

例如我有这两张图片:

图片一:

图片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 蒙版。

希望有人可以帮助我

【问题讨论】:

    标签: php gd php-gd colorize


    【解决方案1】:

    使用imagefilter() 可以更轻松地做到这一点:

    <?php
    $im = imagecreatefrompng('dog.png');
    imagefilter($im, IMG_FILTER_COLORIZE, 255, 0, 0);
    imagepng($im, 'result.png');
    imagedestroy($im);
    

    结果:

    【讨论】:

    • 是的,但现在颜色不对了。它的光已经试过了。
    【解决方案2】:

    imagecolorallocate() 或其 alpha 等效项的文档中没有提到它,但有人指出 in the comments 在用完之前只能在图像中分配 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);
    

    输出:

    【讨论】:

      【解决方案3】:

      我已经用我的代码让它工作了。我所要做的就是添加imagepalettetotruecolor($im);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-27
        • 2010-10-17
        • 2015-04-20
        • 2011-02-05
        • 2011-08-10
        • 1970-01-01
        • 2014-01-10
        • 1970-01-01
        相关资源
        最近更新 更多