如何使用 Carrierwave 和 MiniMagick 使用多个图像制作图像

Man*_*wat 4 ruby ruby-on-rails ruby-on-rails-3 carrierwave minimagick

我有Image模型和Movie模型,Movie可以有很多images. 我正在存储图像的 3 个版本,big, medium and small. 在我的应用程序中,用户可以选择特定尺寸的图像,比如说 4 张“中等”尺寸的图像,然后用户可以共享它们。最少 3 张图片,最多 5 张。

我需要使用所有选定的 4 张中等大小的图像创建一个图像。我不想单独发送这些图像,我想将其作为单个图像发送。

我正在使用CarrierwaveMiniMagick

感谢帮助!

Taa*_*avo 5

假设这里真正的问题是关于用 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
Run Code Online (Sandbox Code Playgroud)

关于此代码的一些说明:

  • source_images 是要合成在一起的图像数组。

  • coordinates是您希望每个图像在最终合成中所处位置的坐标值数组。坐标的索引对应于各自的 source_image 的索引。另请注意,如果坐标为正,则需要包含“+”字符,例如“+50”。(您可能需要尝试找到所需的坐标。)

  • 如果您的图片没有存储在本地,则需要使用source_image.file.url替代的source_image.file.path

  • 这段代码是为了在电影模型的上下文中运行而编写的,但它可以移动到你喜欢的任何地方。