RMagick 使用 alpha 转换图像

RMagick convert image with alpha

我正在尝试通过 RMagick 将图像的不透明度转换为 25%。以下是命令行的工作,但我不知道如何在 Ruby.

中执行
convert input.png -alpha on -channel A -evaluate set 25% +channel output.png

我试过弄乱 Magick::AlphaChannelType::ActivateAlphaChannel 但不知道如何将命令链接在一起。任何帮助将不胜感激!

请尝试使用此功能来解决您的问题

 def watermark(opacity = 0.25, size = 'input')
    manipulate! do |img|
      logo = Magick::Image.read("#{Rails.root}/app/assets/images/{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 = logo.composite(logo_opacity, Magick::NorthWestGravity, 0, 0, Magick::OverCompositeOp)
    end
  end