Search code examples
minimagick

Retrieving the hex code of the color of a given pixel


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.


Solution

  • 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