抛出:IllegalArgumentException:预期范围之外的颜色参数:红,绿,蓝(Ille

2019-09-02 14:53发布

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

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

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?

Answer 1:

您呼叫的颜色构造有三个浮动参数,以便值允许为0.0和1.0之间。

但color.getRed()(蓝色,绿色)可以返回一个值高达255这样你就可以得到如下:

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

这是远远高为1.0F,甚至252的颜色(INT,INT,int)构造允许。 所以,你的规模等因素da​​sblinkenlight说和投灰度为int,否则你会打电话Color.`错误的构造

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


文章来源: IllegalArgumentException: Color parameter outside of expected range: Red Green Blue