ImageMagick / Imagick:将带有 Alpha 通道的 PNG 转换为 2 色图像(彩色、透明)

ImageMagick / Imagick: Convert a PNG with Alpha channel into a 2 color image (Color, Transparent)

我想知道并找出如何 colorize/replace 图像的任何像素,该像素不是(完全)透明的,像素不透明。

例如,有一个带有透明像素的彩色徽标,我想将其转换为只有颜色#ff0000 的徽标,而不更改透明背景。

我想用 PHP Imagick 库实现这一点。我找不到任何好的文档。

我以为Imagick::thresholdImage会是一个帮手,但是没有关于阈值参数的文档

使用这段代码可获得最佳效果。但仍然不能完美地工作。一些像素 - 我猜那些 alpha > 0 和 < 1 的像素不会被替换。

$image = new \Imagick($source);
$image->setImageFormat('png');

$fill = new \ImagickPixel('#ff0000');
$image->thresholdImage(0);
$image->paintOpaqueImage('#ffffff', $fill, 1);

$image->writeImage($destination);

I would like to know and find out, how I can colorize/replace any pixel of an image, that is not (fully) transparent with an opaque pixel.

你几乎肯定不会。

下面的代码可以满足您的要求(我认为)并且输出看起来很糟糕。也许您应该给出一个示例输入图像,以及一个您在 Photoshop 中编辑过的示例输出图像,以显示您的期望。

输入图像:

输出图像:

$imagick = new Imagick("fnord.png");

// Get the alpha channel of the original image.
$imagick->separateImageChannel(\Imagick::CHANNEL_ALPHA);

// Make all the colors above this pure white.
$imagick->whiteThresholdImage("rgb(254, 254, 254)");

// Make all the colors below this pure black.
$imagick->blackThresholdImage("rgb(254, 254, 254)");

// We want the mask the other way round
$imagick->negateImage(false);

$imagickCanvas = new \Imagick();

$imagickCanvas->newPseudoImage(
    $imagick->getImageWidth(),
    $imagick->getImageHeight(),
    "xc:rgb(255, 0, 0)"
);

// Copy the mask back as the alpha channel.
$imagickCanvas->compositeImage($imagick, \Imagick::COMPOSITE_COPYOPACITY, 0, 0);

// Write out the image.
$imagickCanvas->setImageFormat('png');
$imagickCanvas->writeImage("./output.png");