java IllegalArgumentException:超出预期范围的颜色参数:红绿蓝

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

IllegalArgumentException: Color parameter outside of expected range: Red Green Blue

javaimagecolorsrgbillegalargumentexception

提问by Hagi

when I tested my code with JUnit, the following error occured:

当我用 JUnit 测试我的代码时,发生了以下错误:

java.lang.IllegalArgumentException: Color parameter outside of expected range: Red Green Blue

Honestly, I don't know why. My code is not very long, so I would like to post it for better help.

老实说,我不知道为什么。我的代码不是很长,所以我想发布它以获得更好的帮助。

BufferedImage img = ImageIO.read(f);
        for (int w = 0; w < img.getWidth(); w++) {
            for (int h = 0; h < img.getHeight(); h++) {
                Color color = new Color(img.getRGB(w, h));
                float greyscale = ((0.299f * color.getRed()) + (0.587f
                        * color.getGreen()) + (0.144f * color.getBlue()));
                Color grey = new Color(greyscale, greyscale, greyscale);
                img.setRGB(w, h, grey.getRGB());

When I run the JUnit test, eclipse marks up the line with

当我运行 JUnit 测试时,eclipse 用

Color grey = new Color(greyscale, greyscale, greyscale);

So, I suppose the problem might be, that I work with floating numbers and as you can see I recalculate the red, green and blue content of the image.

所以,我想问题可能是,我使用浮点数,正如你所看到的,我重新计算了图像的红色、绿色和蓝色内容。

Could anyone help me to solve that problem?

谁能帮我解决这个问题?

回答by mszalbach

You are calling the Color constructor with three float parameters so the values are allowed to be between 0.0 and 1.0.

您正在使用三个浮点参数调用 Color 构造函数,因此允许值介于 0.0 和 1.0 之间。

But color.getRed() (Blue, Green) can return a value up to 255. So you can get the following:

但是 color.getRed() (Blue, Green) 可以返回一个最大为 255 的值。所以你可以得到以下内容:

float greyscale = ((0.299f *255) + (0.587f * 255) + (0.144f * 255));
System.out.println(greyscale); //262.65

Which is far to high for 1.0f and even for 252 which the Color(int,int,int) constructor allows. So scale your factors like dasblinkenlight said and cast the greyscale to an int or else you will call the wrong constructor of Color.`

这对于 1.0f 甚至是 Color(int,int,int) 构造函数允许的 252 来说都太高了。所以像dasblinkenlight所说的那样缩放你的因素并将灰度转换为int,否则你会调用错误的Color构造函数。`

new Color((int)greyscale,(int)greyscale,(int)greyscale);