检索给定像素的颜色的十六进制代码

时间:2012-01-17 11:56:46

标签: minimagick

我已经将resize_to_fill缩小到[1,1]尺寸,从而将图像缩小为包含基本上整个图像的平均颜色的单个像素(假设图像在高度和宽度之间没有巨大的差异,当然)。 现在我试图以十六进制格式检索这个单个像素的颜色。

在终端窗口中,我可以像这样运行convert命令:

convert image.png txt:
# ImageMagick pixel enumeration: 1,1,255,rgb
0,0: (154,135,116) #9A8774 rgb(154,135,116)

但我不确定如何在图像所属的模型的before_save部分中从应用程序内部运行此命令。 使用carrierwave

上传和附加图像

到目前为止,我已检索到图像:

image = MiniMagick::Image.read(File.open(self.image.path))

但我不太确定如何从这里开始。

3 个答案:

答案 0 :(得分:7)

您可以像这样添加pixel_at方法:

module MiniMagick
  class Image
    def pixel_at(x, y)
      case run_command("convert", "#{escaped_path}[1x1+#{x}+#{y}]", "-depth 8", "txt:").split("\n")[1]
      when /^0,0:.*(#[\da-fA-F]{6}).*$/ then $1
      else nil
      end
    end
  end
end

然后像这样使用它:

i = MiniMagick::Image.open("/path/to/image.png")
puts i.pixel_at(100, 100)

输出:

#34555B

答案 1 :(得分:2)

对于最近版本的MiniMagick,将escaped_path更改为path,如下所示:

module MiniMagick
  class Image
    def pixel_at x, y
      run_command("convert", "#{path}[1x1+#{x.to_i}+#{y.to_i}]", 'txt:').split("\n").each do |line|
        return $1 if /^0,0:.*(#[0-9a-fA-F]+)/.match(line)
      end
      nil
    end
  end
end

答案 2 :(得分:0)

要与Rails 4一起使用,代码需要略有不同:

# config/application.rb

module AwesomeAppName
  class Application < Rails::Application
    config.after_initialize do
      require Rails.root.join('lib', 'gem_ext.rb')
    end
  end
end

# lib/gem_ext.rb
require "gem_ext/mini_magick"

# lib/gem_ext/mini_magick.rb
require "gem_ext/mini_magick/image"

# lib/gem_ext/mini_magick/image.rb
module MiniMagick
  class Image
    def pixel_at(x, y)
      case run_command("convert", "#{path}[1x1+#{x}+#{y}]", "-depth", '8', "txt:").split("\n")[1]
      when /^0,0:.*(#[\da-fA-F]{6}).*$/ then $1
      else nil
      end
    end
  end
end

# example
#$ rails console
image = MiniMagick::Image.open(File.expand_path('~/Desktop/truck.png'))
#=> #<MiniMagick::Image:0x007f9bb8cc3638 @path="/var/folders/1q/fn23z3f11xd7glq3_17vhmt00000gp/T/mini_magick20140403-1936-phy9c9.png", @tempfile=#<File:/var/folders/1q/fn23z3f11xd7glq3_17vhmt00000gp/T/mini_magick20140403-1936-phy9c9.png (closed)>>
image.pixel_at(1,1)
#=> "#01A30D"