开发者

Pixel RGB with ImageMagick and Rails

I'm currently uploading an image with PaperC开发者_如何学JAVAlip 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.


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


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜