例如,在回形针中,当.png转换为.jpg时,可以将其添加到设置白色背景中:
:convert_options => { :all => '-background white -flatten +matte'}
一旦carrierwave也使用rmagick,该怎么做?
Obs。:我的文件存储在S3中。
我的代码:
version :square do
process :resize_to_fill => [200, 200]
process :convert => 'jpg'
end
答案 0 :(得分: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 :(得分: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"]
答案 2 :(得分:0)
使用MiniMagick,我可以这样做:
process :resize_and_pad => [140, 80, "#FFFFFF", "Center"]
答案 3 :(得分: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