Retrieving the hex code of the color of a given pixel

被刻印的时光 ゝ 提交于 2019-12-04 09:59:04

问题


I have used resize_to_fill down to a [1,1] size thus reducing the image to a single pixel containing what is basically the average color of the entire image (provided the image does not have a huge disparity between height and width, of course). Now I'm attempting to retrieve the color of this single pixel in hex format.

From the terminal window I am able to run the convert command like this:

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

I am however uncertain of how I could run this command from inside the application during the before_save section of the model that the image belongs to. The image is uploaded and attached using carrierwave

So far I have retrieved the image:

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

But I'm not quite certain how to procede from here.


回答1:


You could add a pixel_at method like this:

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



回答2:


For recent versions of MiniMagick change escaped_path to path like this:

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



回答3:


To use with Rails 4 the code needs to 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"


来源:https://stackoverflow.com/questions/8894194/retrieving-the-hex-code-of-the-color-of-a-given-pixel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!