如何使用Magick ++将透明背景的不透明度设置为png图像

时间:2015-05-29 16:29:57

标签: c++ magick++

我使用ImageMagick渲染图像。 我打开png file作为Magick :: Image并在另一个Magick :: Image上绘制并将不透明度设置为png图像。并将其另存为jpg file

在保存的文件中,透明背景变为黑色。

示例代码:

    Image newImage;
    newImage.size(Geometry(1000, 1000));
    newImage.fillColor(Color(50, TransparentOpacity / 2, 50));
    newImage.draw(DrawableRectangle(0, 0, 1000, 1000));

    Image originalImage("test-Image-1.png");
    originalImage.opacity(TransparentOpacity / 2);
    newImage.composite( originalImage, 300, 100, AtopCompositeOp );

    newImage.magick("JPG");
    newImage.write("testImage3.jpg");

是否可以将50%的透明度设置为图像并将背景设置为完全透明?

1 个答案:

答案 0 :(得分:1)

问题在于:

originalImage.opacity(TransparentOpacity / 2);

来源“test-Image-1.png”有一个看起来像......的alpha通道。

Orignal alpha channel

当您将不透明度设置为50%时,您将设置整个频道,而不是将级别降低50%。用originalImage.opacity改变的alpha通道现在看起来像这样......

50% alpha-channel

有很多方法可以将Alpha通道更改为降低图像不透明度。 Pixel iterationFXlevel color仅举几例。我喜欢隔离alpha通道,改变电平,并将频道复制回图像。以下示例只是将颜色值“交换”为50%不透明度== gray50

Image originalImage("test-Image-1.png");
Image mask(originalImage); // Clone image
mask.channel(OpacityChannel); // Isolate alpha-channel
/*
  For this example I'll mimic CLI options:
  "-fuzz 50% -fill gray50 -opaque black"
*/
mask.colorFuzz(MaxRGB * 0.5);
mask.opaque(Color("black"), Color("gray50"));
mask.negate();
// Copy mask image as new alpha-channel
originalImage.composite( mask, 0, 0, CopyOpacityCompositeOp );

Reduced opacity by 50%

现在,您可以在不担心黑色背景的情况下合成另一张图像。