Java BufferedImage 分别获得红色、绿色和蓝色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2615522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java BufferedImage getting red, green and blue individually
提问by deltanovember
The getRGB()
method returns a single int. How can I get individually the red, green and blue colors all as the values between 0 and 255?
该getRGB()
方法返回一个整数。如何分别获得红色、绿色和蓝色作为 0 到 255 之间的值?
采纳答案by Michael Mrozek
回答by Matti Virkkunen
You'll need some basic binary arithmetic to split it up:
你需要一些基本的二进制算术来拆分它:
int blue = rgb & 0xFF;
int green = (rgb >> 8) & 0xFF;
int red = (rgb >> 16) & 0xFF;
(Or possibly the other way round, I honestly can't remember and the documentation isn't giving me an instant answer)
(或者可能反过来,老实说我不记得了,文档也没有给我一个即时的答案)
回答by Jo?o Silva
A pixel is represented by a 4-byte (32 bit) integer, like so:
一个像素由一个 4 字节(32 位)整数表示,如下所示:
00000000 00000000 00000000 11111111
^ Alpha ^Red ^Green ^Blue
So, to get the individual color components, you just need a bit of binary arithmetic:
因此,要获得各个颜色分量,您只需要进行一些二进制算术:
int rgb = getRGB(...);
int red = (rgb >> 16) & 0x000000FF;
int green = (rgb >>8 ) & 0x000000FF;
int blue = (rgb) & 0x000000FF;
This is indeed what the java.awt.Color
class methods do:
这确实是java.awt.Color
类方法所做的:
553 /**
554 * Returns the red component in the range 0-255 in the default sRGB
555 * space.
556 * @return the red component.
557 * @see #getRGB
558 */
559 public int getRed() {
560 return (getRGB() >> 16) & 0xFF;
561 }
562
563 /**
564 * Returns the green component in the range 0-255 in the default sRGB
565 * space.
566 * @return the green component.
567 * @see #getRGB
568 */
569 public int getGreen() {
570 return (getRGB() >> 8) & 0xFF;
571 }
572
573 /**
574 * Returns the blue component in the range 0-255 in the default sRGB
575 * space.
576 * @return the blue component.
577 * @see #getRGB
578 */
579 public int getBlue() {
580 return (getRGB() >> 0) & 0xFF;
581 }
回答by Defd
For simple color manipulations, you can use
对于简单的颜色操作,您可以使用
bufImg.getRaster().getPixel(x,y,outputChannels)
The outputChannels is an array for storing the fetched pixel. Its length depends on your image's actual channel count. For example, an RGB image has 3 channels; and an RGBA image has 4 channels.
outputChannels 是一个数组,用于存储获取的像素。它的长度取决于图像的实际通道数。例如,RGB 图像有 3 个通道;RGBA 图像有 4 个通道。
This method has 3 output types: int, float and double. To get a color value ranges from 0~255, your actual parameter outputChannels should be an int[] array.
该方法有 3 种输出类型:int、float 和 double。要获得 0~255 范围内的颜色值,您的实际参数 outputChannels 应该是一个 int[] 数组。