2013-07-24 32 views
4

我有Image型號和Movie型號和Movie可以有多個images。我正在存儲3個版本的圖像,big, medium and small。 在我的應用程序中,用戶可以選擇特定尺寸的圖像,可以說4個「中」尺寸的圖像,然後用戶可以共享它們。最少3張圖片和最多5.如何使用Carrierwave和MiniMagick使用多個圖像製作圖像

我需要創建一個圖像與所有選定的4箇中等大小的圖像。我不想單獨發送這些圖像,我想將它作爲單個圖像發送。我使用CarrierwaveMiniMagick

感謝您的幫助!

回答

3

假設這裏真正的問題是關於用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

  • 此代碼被編寫爲在電影模型的上下文中運行,但它可以隨意移動。

相關問題