我正在尝试创建一个具有不同不透明度值的水印(从0不透明值到1完全透明)。
我在ruby中有以下RMagick方法:
# 0 = opaque (Magick::OpaqueOpacity) 1= transparent (Magick::TransparentOpacity)
def watermark(opacity = 0.99, size = 'm')
manipulate! do |img|
logo = Magick::Image.read("#{Rails.root}/app/assets/images/watermark#{size}.png").first
logo.alpha(Magick::ActivateAlphaChannel)
logo.opacity = (1 - opacity.to_f) * Magick::QuantumRange
img.alpha(Magick::ActivateAlphaChannel)
img = img.composite(logo, Magick::NorthWestGravity, 0, 0, Magick::OverCompositeOp)
end
end
我的问题是它似乎有效,但复合模式或alpha合成或设置不透明度或alpha失败,因为我在图像中得到黑色透明度。例如,如果我的水印是带有文字的完全透明的图像,我将其放在汽车图像上,那么我会得到一个带有水印的更暗或夜间图像,因此水印的背景不能正确混合。
有关正确设置水印图像中不透明度的建议吗?也许有一些解决水印的方法?
编辑:添加图片示例:
http://uppix.com/f-watermarkg53925b100016ab8e.png(水印) http://oi62.tinypic.com/2us8rxl.jpg(基本图片) http://oi60.tinypic.com/2pt6mg3.jpg(作文)
答案 0 :(得分:6)
感谢Neil Slater,我终于找到了正确的解决方案。在我的最终结果中我需要composite operation DstIn + Over的组合:
def watermark(opacity = 0.99, size = 'm')
manipulate! do |img|
logo = Magick::Image.read("#{Rails.root}/app/assets/images/watermark#{size}.png").first
logo.alpha(Magick::ActivateAlphaChannel)
white_canvas = Magick::Image.new(logo.columns, logo.rows) { self.background_color = "none" }
white_canvas.alpha(Magick::ActivateAlphaChannel)
white_canvas.opacity = Magick::QuantumRange - (Magick::QuantumRange * opacity)
# Important: DstIn composite operation (white canvas + watermark)
logo_opacity = logo.composite(white_canvas, Magick::NorthWestGravity, 0, 0, Magick::DstInCompositeOp)
logo_opacity.alpha(Magick::ActivateAlphaChannel)
# Important: Over composite operation (original image + white canvas watermarked)
img = img.composite(logo_opacity, Magick::NorthWestGravity, 0, 0, Magick::OverCompositeOp)
end
end