【问题标题】:ImageMagick / Imagick: Convert a PNG with Alpha channel into a 2 color image (Color, Transparent)ImageMagick / Imagick:将带有 Alpha 通道的 PNG 转换为 2 色图像(彩色、透明)
【发布时间】:2016-07-24 06:13:06
【问题描述】:

我想知道并找出如何用不透明像素着色/替换图像的任何像素,即不(完全)透明的像素。

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

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

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

使用此代码片段可获得最佳结果。但仍然不能完美地工作。一些像素 - 我猜那些 alpha > 0 和

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

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

$image->writeImage($destination);

【问题讨论】:

  • 我不是 100% 确定您真正想要做什么,但我认为您希望将您的 alpha/透明度通道限制为 100% 或 0% 且没有中间值,因此您需要设置阈值你的 alpha 通道,所以我想你想设置背景颜色,然后做类似thresholdImage(Imagick::getQuantum()-1,imagick::CHANNEL_ALPHA)

标签: php imagemagick imagick


【解决方案1】:

我想知道并找出如何用不透明像素着色/替换图像的任何像素,即不(完全)透明的像素。

你几乎肯定不会。

下面的代码符合您的要求(我认为),输出看起来很糟糕。或许您应该提供一个示例输入图像和一个您在 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");

【讨论】:

  • 谢谢,伙计。就是这个。即使输出看起来很糟糕。这正是所需的输出。 (在我的用例中,不会有像您的示例中那样具有 alpha 值的大(ger)区域。即使大多数请求的图像包含更多具有更大半不透明区域的模糊轮廓,我也可以调整阈值以获得将妥协。
猜你喜欢
  • 2011-03-23
  • 1970-01-01
  • 2012-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多