【问题标题】:How make a image using multiple images using Carrierwave and MiniMagick如何使用 Carrierwave 和 MiniMagick 使用多个图像制作图像
【发布时间】:2013-07-24 10:38:42
【问题描述】:
我有Image 模型和Movie 模型,Movie 可以有很多images。我正在存储图像的 3 个版本,big, medium and small。
在我的应用程序中,用户可以选择特定尺寸的图像,比如说 4 张“中等”尺寸的图像,然后用户可以分享它们。最少 3 张图片,最多 5 张图片。
我需要创建一个包含所有选定的 4 张中等尺寸图像的图像。我不想单独发送这些图像,我想将其作为单个图像发送。
我正在使用Carrierwave 和MiniMagick。
感谢您的帮助!
【问题讨论】:
标签:
ruby-on-rails
ruby
ruby-on-rails-3
carrierwave
minimagick
【解决方案1】:
假设这里的真正问题是关于使用 minimagick 合成图像,这里有一些代码。请注意,我在 Movie 中添加了一个名为“composite_image”的字段,并且我决定附加到 Image 的上传器名为“file”。
def render_composite_image(source_images, coordinates)
temp_file = TempFile.new(['render_composite_image', '.jpg'])
img = MiniMagick::Image.new(temp_file.path)
img.run_command(:convert, "-size", "#{ COMPOSITE_WIDTH }x#{ COMPOSITE_HEIGHT }", "xc:white", img.path)
source_images.each_with_index do |source_image, i|
resource = MiniMagick::Image.open(source_image.file.path)
img = img.composite(resource) do |composite|
composite.geometry "#{ coordinates[i].x }x#{ coordinates[i].y }"
end
end
img.write(temp_file.path)
self.update_attributes(composite_image: temp_file)
end
关于这段代码的几点说明:
source_images 是您要合成在一起的一组图像。
coordinates 是您希望每个图像在最终合成中的位置的坐标值数组。坐标的索引对应于相应的 source_image 的索引。另请注意,如果坐标为正数,则需要包含“+”字符,例如“+50”。 (您可能需要尝试找到所需的坐标。)
如果您的图片未存储在本地,则需要使用source_image.file.url 而不是source_image.file.path。
此代码是为在电影模型的上下文中运行而编写的,但它可以移动到您喜欢的任何位置。