Pixel RGB with ImageMagick and Rails

眉间皱痕 提交于 2019-12-04 03:57:05

问题


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.


回答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.




回答2:


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



回答3:


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)



来源:https://stackoverflow.com/questions/6499161/pixel-rgb-with-imagemagick-and-rails

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