如何为水印图像创建一个重要的 ActiveStorage 变体?
How do I create a non-trivial ActiveStorage variant for watermarking images?
我编写了以下 ImageMagick 命令,它获取水印图像、对其进行缩放并将其合成到基础图像上、平铺:
convert image.png \( watermark.png -resize 5% -write mpr:watermark +delete \) \( +clone -tile mpr:watermark -draw "color 0,0 reset" \) -compose over -composite watermarked_image.png
我想将其定义为 Active Storage 变体,这样我就可以在某些情况下为图像添加水印,但我做空了。我只能找到非常简单的转换示例。这可能作为 Active Storage 变体吗?
我终于弄明白了,想分享答案以防其他人在这里寻求帮助。我找到 the following article, which explains the basic premise. From there it was only a matter of translating the ImageMagick command into the correct MiniMagick API 个调用。
require "image_processing"
module ImageProcessing
module MiniMagick
module Processing
extend ActiveSupport::Concern
included do
def watermark(scale: 0.5, opacity: 0.5)
watermark_path = Rails.root.join('lib', 'watermark.png')
formatted_scale = "%0.0f%%" % [scale* 100]
magick.stack do |stack|
stack << watermark_path
stack.alpha('on')
stack.channel('a')
stack.evaluate('multiply', opacity.to_f)
stack.channel.+
stack.resize(formatted_scale)
stack.write('mpr:watermark')
stack.delete.+
end
magick.stack do |stack|
stack.clone.+
stack.tile('mpr:watermark')
stack.draw('color 0,0 reset')
end
magick.compose('over')
magick.composite
end
end
end
end
end
ImageProcessing::MiniMagick::Processor.include(
ImageProcessing::MiniMagick::Processing
)
然后,假设您有一个带有 image
附件的模型,只需使用以下命令调用新的水印变体:
design.image.variant(
watermark: { scale: 0.25, opacity: 0.2 },
)
我编写了以下 ImageMagick 命令,它获取水印图像、对其进行缩放并将其合成到基础图像上、平铺:
convert image.png \( watermark.png -resize 5% -write mpr:watermark +delete \) \( +clone -tile mpr:watermark -draw "color 0,0 reset" \) -compose over -composite watermarked_image.png
我想将其定义为 Active Storage 变体,这样我就可以在某些情况下为图像添加水印,但我做空了。我只能找到非常简单的转换示例。这可能作为 Active Storage 变体吗?
我终于弄明白了,想分享答案以防其他人在这里寻求帮助。我找到 the following article, which explains the basic premise. From there it was only a matter of translating the ImageMagick command into the correct MiniMagick API 个调用。
require "image_processing"
module ImageProcessing
module MiniMagick
module Processing
extend ActiveSupport::Concern
included do
def watermark(scale: 0.5, opacity: 0.5)
watermark_path = Rails.root.join('lib', 'watermark.png')
formatted_scale = "%0.0f%%" % [scale* 100]
magick.stack do |stack|
stack << watermark_path
stack.alpha('on')
stack.channel('a')
stack.evaluate('multiply', opacity.to_f)
stack.channel.+
stack.resize(formatted_scale)
stack.write('mpr:watermark')
stack.delete.+
end
magick.stack do |stack|
stack.clone.+
stack.tile('mpr:watermark')
stack.draw('color 0,0 reset')
end
magick.compose('over')
magick.composite
end
end
end
end
end
ImageProcessing::MiniMagick::Processor.include(
ImageProcessing::MiniMagick::Processing
)
然后,假设您有一个带有 image
附件的模型,只需使用以下命令调用新的水印变体:
design.image.variant(
watermark: { scale: 0.25, opacity: 0.2 },
)