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

5
例如,在Paperclip中,当将.png转换为.jpg时,可以添加以下内容以设置白色背景:
:convert_options => { :all => '-background white -flatten +matte'}

一旦CarrierWave也使用了RMagick,该如何处理?
注意:我的文件存储在S3中。
我的代码:
version :square do
    process :resize_to_fill => [200, 200]
    process :convert => 'jpg'
end
4个回答

2
这里是一个更加清晰的版本,只进行转换和背景填充。
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"]

1
使用MiniMagick,我只需这样做:
``` process :resize_and_pad => [140, 80, "#FFFFFF", "Center"] ```

1

使用MiniMagick的解决方案:首先,在上传程序中定义一个方法,将图像转换为jpg格式,并删除alpha通道并将背景颜色设置为白色:

def convert_to_jpg(bg_color = '#FFFFFF')
  manipulate! do |image|
    image.background(bg_color)
    image.alpha('remove')
    image.format('jpg')
  end
end

然后添加一个新版本,将文件转换为jpg格式(还要覆盖full_filename方法以更改文件名的扩展名):

version :jpg do
  process :convert_to_jpg

  def full_filename(file)
    filename = super(file)
    basename = File.basename(filename, File.extname(filename))
    return "#{basename}.jpg"
  end
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接