Carrierwave PNG到JPG转换器.如何避免黑色背景?

Luc*_*cas 5 ruby-on-rails rmagick imagemagick paperclip carrierwave

例如,在回形针中,当.png转换为.jpg时,可以将其添加到设置白色背景中:

:convert_options => { :all => '-background white -flatten +matte'}
Run Code Online (Sandbox Code Playgroud)

一旦carrierwave也使用了rmagick,该怎么做?

视频:我的文件存储在S3中.

我的代码:

version :square do
    process :resize_to_fill => [200, 200]
    process :convert => 'jpg'
end
Run Code Online (Sandbox Code Playgroud)

Luc*_*cas 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
Run Code Online (Sandbox Code Playgroud)