获取BufferedImage的RGB [英] Get RGB of a BufferedImage

查看:109
本文介绍了获取BufferedImage的RGB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以解释如何从BufferedImage获取rgb值数组吗?

Can anybody explain how to get an array of rgb value from a BufferedImage?

我在BufferedImage中有一个灰度图像,需要提取一个0到255个描述图像的数组。

我知道BufferedImage是正确的,因为我可以将它保存到PNG。但是,如果我使用 int [] dataBuffInt =((DataBufferInt)heightMap.getDataBuffer())。getData(); 我得到一堆巨大的负数。

I have a grey scale image in a BufferedImage and need to extract an array of 0 to 255 values that describe the image.
I know the BufferedImage is correct because I can save it to PNG. However, if I use int[] dataBuffInt = ((DataBufferInt) heightMap.getDataBuffer()).getData(); I get a bunch of huge negative numbers.

我已经搜索了一段时间并看到了一些转移某些值的引用( post )但不太明白他们在说什么。

I have searched for a while and seen some references to shifting some values (post) but don't really understand what they are saying.

基本上我想从BufferedImage转到0到25​​5 RBG值的数组。

我不确定我是否正确解释了自己,需要更多详细信息。

Basically I want to go from a BufferedImage to an array of 0 to 255 RBG values.
I'm not sure I explained myself properly, plaese ask for more details is needed.

编辑:

@Garbage感谢您的提示。我试过int [] dataBuffInt = heightMap.getRGB(0,0,heightMap.getWidth(),heightMap.getHeight(),null,0,heightMap.getWidth());但得到相同的结果。

@Greg Kopff结果是2,它被设置为TYPE_INT_ARGB


@Garbage Thanks for the tip. I tried int[] dataBuffInt = heightMap.getRGB(0, 0, heightMap.getWidth(), heightMap.getHeight(), null, 0, heightMap.getWidth()); But get the same result.
@Greg Kopff The result is 2 and it was set to TYPE_INT_ARGB

推荐答案

您得到负数,因为您从其中一个像素获得的int值由红色,绿色,蓝色和alpha组成。您需要拆分颜色以获取每个颜色组件的值。

You get negative numbers since the int value you get from one of the pixels are composed by red, green, blue and alpha. You need to split the colors to get a value for each color component.

最简单的方法是创建 Color 对象并使用 getRed getGreen getBlue (以及 getAlpha )获取组件的方法:

The simplest way to do this is to create a Color object and use the getRed, getGreen and getBlue (aswell as getAlpha) methods to get the components:

public static void main(String... args) throws Exception {

    BufferedImage image = ImageIO.read(
         new URL("http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png"));

    int w = image.getWidth();
    int h = image.getHeight();

    int[] dataBuffInt = image.getRGB(0, 0, w, h, null, 0, w); 

    Color c = new Color(dataBuffInt[100]);

    System.out.println(c.getRed());   // = (dataBuffInt[100] >> 16) & 0xFF
    System.out.println(c.getGreen()); // = (dataBuffInt[100] >> 8)  & 0xFF
    System.out.println(c.getBlue());  // = (dataBuffInt[100] >> 0)  & 0xFF
    System.out.println(c.getAlpha()); // = (dataBuffInt[100] >> 24) & 0xFF
}

输出:

173
73
82
255

这篇关于获取BufferedImage的RGB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆