0

我使用以下内容:convert_options

-auto-orient -gravity center -background transparent -extent '50x50>'

对于我的 has_attached_file 调用,我想做的不是使用透明,而是将图像的背景颜色设置为图像 0,0 处的颜色。

使用

convert rose: -format "%[pixel:u.p{0,0}]" info:-

我得到输出

srgb(48,47,45)

这很好,但我无法在实际通话中使用它来代替透明......

谁能帮我解决这个问题?

4

1 回答 1

4

为此编写了一个自定义插值器。

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
于 2012-09-26T16:38:13.770 回答