Java 从ColorModel获取RGB组件
我想提取图像像素的R、G和B值。我有两种方法Java 从ColorModel获取RGB组件,java,colors,rgb,pixel,raster,Java,Colors,Rgb,Pixel,Raster,我想提取图像像素的R、G和B值。我有两种方法 File img_file = new File("../foo.png"); BufferedImage img = ImageIO.read(img_file); 第一种方法(效果良好): 第二种方法(抛出新的IllegalArgumentException(“每个像素有多个组件”)) 这种行为的原因是什么?通常,当我想从缓冲区图像中提取RGB时,我会执行以下操作: File img_file = new File("../foo.png");
File img_file = new File("../foo.png");
BufferedImage img = ImageIO.read(img_file);
第一种方法(效果良好):
第二种方法(抛出新的IllegalArgumentException(“每个像素有多个组件”))
这种行为的原因是什么?通常,当我想从
缓冲区图像中提取RGB时,我会执行以下操作:
File img_file = new File("../foo.png");
BufferedImage img = ImageIO.read(img_file);
Color color = new Color(img.getRGB(i,j));
int red = color.getRed();
基于
如果此项的像素值为0,则引发IllegalArgumentException
ColorModel不能方便地表示为单个int
这表明基础颜色模型可以用一个int
值表示
您可能还想了解更多详细信息
通常,您只需从图像中获取压缩像素int
,并使用Color
生成Color
表示,然后从中提取值
首先,在x/y
处获取像素的int
压缩值
int pixel = img.getRGB(i, j);
使用此选项可构造颜色
对象
Color color = new Color(pixel, true); // True if you care about the alpha value...
提取R、G、B值
int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();
现在,您可以简单地做一些数学运算,但这更简单,可读性更强-IMHO感谢您的回复。但是如何确定颜色模型是否可以用单个int值表示呢?就个人而言,我会检查它是否是ComponentColorModel
,IndexColorModel
或PackedColorModel
的实例,但您也可以测试getNumColorComponents
,getNumComponents
和getPixelSize
return…@Rayhunter,BufferedImage
最多只支持32位类型,所以所有像素都可以放在一个Java int中(请参阅支持的类型)。我刚刚注意到intpxl=img.getRGB(I,j)
返回-1
,至少对我来说是wierd。@Rayhunter不,这是完全正常的,并且与打包的int
如何处理/允许溢出有关。记住int
值是一系列压缩的字节
Color color = new Color(pixel, true); // True if you care about the alpha value...
int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();