为此编写了一个自定义插值器。
module Paperclip
class BgExtrapolator < Processor
def initialize(file, options = {}, attachment = nil)
super
@file = file
@instance = options[:instance]
@current_format = File.extname(@file.path)
@basename = File.basename(@file.path, @current_format)
end
def make
src = @file
dst = Tempfile.new([@basename, @format ? ".#{@format}" : ''])
dst.binmode
begin
# grab the image
logo = Magick::Image.read(src.path).first
# determine the color of the upper left most pixel
bg_color = logo.pixel_color(0,0)
# construct an rgba value to provide to imagemagick
bg_color_value = "rgba(#{bg_color.red >> 8},#{bg_color.green >> 8},#{bg_color.blue >> 8},#{bg_color.to_hsla[3]})"
parameters = []
parameters << ":source"
parameters << "-resize '#{options[:geometry].to_s}' -auto-orient -gravity center -background '#{bg_color_value}' -extent '#{options[:geometry].to_s}'"
parameters << ":dest"
# clean the command
parameters = parameters.flatten.compact.join(" ").strip.squeeze(" ")
# run the command
success = convert(parameters, :source => File.expand_path(src.path), :dest => File.expand_path(dst.path))
rescue Cocaine::ExitStatusError => e
raise Paperclip::Error, "There was an error processing the thumbnail for #{@basename}" if @whiny
rescue Cocaine::CommandNotFoundError => e
raise Paperclip::Errors::CommandNotFoundError.new("Could not run the `convert` command. Please install ImageMagick.")
end
dst
end
end
end