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

问题描述 投票:5回答:4

例如,在回形针中,当.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
ruby-on-rails imagemagick paperclip carrierwave rmagick
4个回答
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

1
投票

这是更纯粹的版本,只进行转换和背景填充

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"]

0
投票

使用MiniMagick,我可以这样做:

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


0
投票

我使用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
© www.soinside.com 2019 - 2024. All rights reserved.