Pixel RGB with ImageMagick and Rails
Asked Answered
B

3

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.

Bloodhound answered 27/6, 2011 at 21:29 Comment(0)
M
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.

Marlyn answered 27/6, 2011 at 22:29 Comment(2)
This definitely helps. I ended up just dividing the RGB values by 257 (QuantumDepth 16 / QuantumDepth 8).Bloodhound
Maybe also look at the quantize method imagemagick.org/RMagick/doc/image3.html#quantize.Marlyn
S
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
Sheley answered 24/6, 2014 at 9:10 Comment(0)
K
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)

Kylstra answered 10/7, 2017 at 9:30 Comment(0)
M
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.

Marlyn answered 27/6, 2011 at 22:29 Comment(2)
This definitely helps. I ended up just dividing the RGB values by 257 (QuantumDepth 16 / QuantumDepth 8).Bloodhound
Maybe also look at the quantize method imagemagick.org/RMagick/doc/image3.html#quantize.Marlyn

© 2022 - 2024 — McMap. All rights reserved.