Getting the hex color code of a given pixel

I used resize_to_fill to a size of [1,1], thus reducing the image to one pixel containing what is basically the middle color of the whole image (assuming the image doesn't have much difference between the height and width, of course). Now I am trying to get the color of this single pixel in hexadecimal format.

In the terminal window, I can run the convert command as follows:

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

However, I do not know how I can run this command from the application during the before_save section of the model to which the image belongs. The image is loaded and attached using the carrier.

So far, I got the image:

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

But I'm not quite sure how to get out of here.

+4
source share
3 answers

You can add the pixel_at method as follows:

 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 

And then use it like this:

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

Outputs:

 #34555B 
+7
source

For recent versions of MiniMagick, change escaped_path to path as follows:

 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
source

For use with Rails 4, the code should be slightly different:

 # 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" 
0
source

Source: https://habr.com/ru/post/1391426/


All Articles