2012-01-17 32 views
4

我已經使用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)) 

但我不是很肯定如何從這裏PROCEDE。

回答

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 
+0

啊,好極了!這完美的做法,謝謝! – 2012-01-17 13:24:11

+0

很酷。我現在確定如果你在圖像外面戳,或者如果有一個alpha通道,它將會如何。所以請注意:) – 2012-01-17 13:28:46

+0

我認爲把圖像縮小到1px×1px的大小應該可以消除這個問題,但絕對值得記住另一個實現。 – 2012-01-17 14:01:45

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 
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" 
相關問題