[英]IllegalArgumentException: Color parameter outside of expected range: Red Green Blue
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? 谁能帮我解决这个问题?
You are calling the Color constructor with three float parameters so the values are allowed to be between 0.0 and 1.0. 您正在使用三个float参数来调用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()(蓝色,绿色)最多可以返回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. 对于1.0f甚至对于Color(int,int,int)构造函数允许的252来说,这都是很高的。 So scale your factors like dasblinkenlight said and cast the greyscale to an int or else you will call the wrong constructor of Color.` 因此,请像dasblinkenlight所说的那样缩放因子,并将灰度转换为int,否则将调用错误的Color构造函数。
new Color((int)greyscale,(int)greyscale,(int)greyscale);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.