Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 257
Luccas Avatar asked Jul 11 '12 20:07

Luccas


2 Answers

Here's saner version that only does the conversion and background filling

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

Example usage:

process convert_and_fill: [:jpg, "#FFFFFF"]
like image 199
inket Avatar answered Sep 21 '22 14:09

inket


Using MiniMagick, I can just do this:

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

like image 42
coderberry Avatar answered Sep 21 '22 14:09

coderberry