我已经解决了这个问题,但我不确定这是否是最好的方法:
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