duanchique1196 2016-04-04 15:42
浏览 683
已采纳

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

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.

For example, having a multicolored Logo with transparent pixels, I would like to convert it in to a logo with only the color #ff0000, and not change the transparent background.

I want to achieve this with the PHP Imagick Library. I cannot find any good documentation.

I thought that Imagick::thresholdImage would be a helper, but there is no documentation about the threshold parameter.

Best results are achieved with this fragment of code. But still not working perfectly. Some pixels - i guess those with alpha > 0 and < 1 are not replaced.

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

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

$image->writeImage($destination);
  • 写回答

1条回答 默认 最新

  • dongsun2789 2016-04-04 19:09
    关注

    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.

    You almost certainly don't.

    The code below does what you are asking (I think) and the output looks terrible. Perhaps you should give an example input image, and a hoped for example output image, that you have edited in Photoshop, to show what you were hoping for.

    Input image:

    enter image description here

    Output image:

    enter image description here

    $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");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题