2012-07-11 107 views
4

在回形針,例如,它可以添加此功能來設置白色背景時巴紐轉換爲JPG格式:Carrierwave PNG到JPG轉換器。如何避免黑色背景?

:convert_options => { :all => '-background white -flatten +matte'} 

一旦carrierwave使用rmagick過,那怎麼辦?

Obs .:我的文件存儲在S3中。

我的代碼:

version :square do 
    process :resize_to_fill => [200, 200] 
    process :convert => 'jpg' 
end 

回答

1

我已經解決了這個問題,但我不知道這是最好的辦法:

def resize_to_fill(width, height, gravity = 'Center', color = "white") 
    manipulate! do |img| 
     cols, rows = img[:dimensions] 
     img.combine_options do |cmd| 
     if width != cols || height != rows 
      scale = [width/cols.to_f, height/rows.to_f].max 
      cols = (scale * (cols + 0.5)).round 
      rows = (scale * (rows + 0.5)).round 
      cmd.resize "#{cols}x#{rows}" 
     end 
     cmd.gravity gravity 
     cmd.background "rgba(255,255,255,0.0)" 
     cmd.extent "#{width}x#{height}" if cols != width || rows != height 
     end 
     ilist = Magick::ImageList.new 
     rows < cols ? dim = rows : dim = cols 
     ilist.new_image(dim, dim) { self.background_color = "#{color}" } 
     ilist.from_blob(img.to_blob) 
     img = ilist.flatten_images 
     img = yield(img) if block_given? 
     img 
    end 
    end 
0

使用MiniMagick,我可以這樣做:

process :resize_and_pad => [140, 80, "#FFFFFF", "Center"]

1

這裏有理智的版本,僅執行轉換和backgro UND填充

def convert_and_fill(format, fill_color) 
    manipulate!(format: format) do |img| 
    new_img = ::Magick::Image.new(img.columns, img.rows) 
    new_img = new_img.color_floodfill(1, 1, ::Magick::Pixel.from_color(fill_color)) 
    new_img.composite!(img, ::Magick::CenterGravity, ::Magick::OverCompositeOp) 
    new_img = yield(new_img) if block_given? 
    new_img 
    end 
end 

實例:

process convert_and_fill: [:jpg, "#FFFFFF"]