如何在 Java 中将 getRGB(x,y) 整数像素转换为 Color(r,g,b,a)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2534116/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:58:02  来源:igfitidea点击:

How to convert getRGB(x,y) integer pixel to Color(r,g,b,a) in Java?

javaimagecolors

提问by Gabriel A. Zorrilla

I have the integer pixel I got from getRGB(x,y), but I don't have any clue about how to convert it to RGBA format. For example, -16726016should be Color(0,200,0,255). Any tips?

我有我从中获得的整数像素getRGB(x,y),但我不知道如何将其转换为 RGBA 格式。例如,-16726016应该是Color(0,200,0,255)。有小费吗?

采纳答案by AKX

If I'm guessing right, what you get back is an unsigned integer of the form 0xAARRGGBB, so

如果我猜对了,你得到的是一个无符号整数形式0xAARRGGBB,所以

int b = (argb)&0xFF;
int g = (argb>>8)&0xFF;
int r = (argb>>16)&0xFF;
int a = (argb>>24)&0xFF;

would extract the color components. However, a quick look at the docssays that you can just do

将提取颜色成分。但是,快速查看文档说你可以做

Color c = new Color(argb);

or

或者

Color c = new Color(argb, true);

if you want the alpha component in the Color as well.

如果您还想要颜色中的 alpha 组件。

UPDATE

更新

Red and Blue components are inverted in original answer, so the right answer will be:

红色和蓝色分量在原始答案中颠倒了,所以正确的答案是:

int r = (argb>>16)&0xFF;
int g = (argb>>8)&0xFF;
int b = (argb>>0)&0xFF;

updated also in the first piece of code

也在第一段代码中更新

回答by laher

    Color c = new Color(-16726016, true);
    System.out.println(c.getRed());
    System.out.println(c.getGreen());
    System.out.println(c.getBlue());
    System.out.println(c.getAlpha());

prints out:

打印出来:

0
200
0
255

Is that what you mean?

你是这个意思吗?