Search code examples
ruby-on-railsimagemagickpaperclipcarrierwavermagick

Carrierwave PNG to JPG converter. How to avoid black background?


In paperclip, for example, it is possible to add this to set white background when .png is converted to .jpg:

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

Once carrierwave uses rmagick too, how to do that?

Obs.: My files are being stored in S3.

My code:

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

Solution

  • I've solved the problem, but I'm not sure if this is the best approach:

    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