4

I'm currently uploading an image with PaperClip and ImageMagick. I would like to get the image's average color so I'm doing this (with a before_create hook):

def get_average_color           
    img =  Magick::Image.read(self.url).first
    pix = img.scale(1, 1)
    averageColor = pix.pixel_color(0,0)
end 

This works but when I try to print the pixel colors out I get them like this:

red=36722, green=44474, blue=40920, opacity=0 

How can I get these RGB values into regular (0-255) RGB values. Do I just mod them? Thanks in advance.

Nakilon
  • 34,866
  • 14
  • 107
  • 142
dshipper
  • 3,489
  • 4
  • 30
  • 41

3 Answers3

3

If ImageMagick is compiled with a quantum depth of 16 bits, and you need the 8 bit values, you can use bitwise operation:

r_8bit = r_16bit & 255;
g_8bit = g_16bit & 255;
b_8bit = b_16bit & 255;

Bitwise operation are much more faster ;)

You can use also this way:

IMAGE_MAGICK_8BIT_MASK = 0b0000000011111111
r_8bit = (r_16bit & IMAGE_MAGICK_8BIT_MASK)
...

Now a little bit of Math:

x_16bit = x_8bit*256 + x_8bit = x_8bit<<8 | x_8bit
user1823890
  • 704
  • 8
  • 7
2

You can easily get 8-bit encoded color using this approach:

averageColor = pix.pixel_color(0,0).to_color(Magick::AllCompliance, false, 8, true)

You can get more details at https://rmagick.github.io/struct.html (to_color paragraph)

Serhii Nadolynskyi
  • 5,473
  • 3
  • 21
  • 20
1

Your ImageMagick is compiled for a quantum depth of 16 bits, versus 8 bits. See this article in the RMagick Hints & Tips Forum for more information.

reducing activity
  • 1,985
  • 2
  • 36
  • 64
Yardboy
  • 2,777
  • 1
  • 23
  • 29
  • This definitely helps. I ended up just dividing the RGB values by 257 (QuantumDepth 16 / QuantumDepth 8). – dshipper Jun 29 '11 at 04:26
  • Maybe also look at the quantize method http://www.imagemagick.org/RMagick/doc/image3.html#quantize. – Yardboy Jun 29 '11 at 13:17