5

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?

Hagi
  • 87
  • 1
  • 1
  • 5
  • 1
    Doesn't the error say it all, or am I missing something? You went too high? – keyser May 11 '13 at 13:05
  • 1) For better help sooner, post an [SSCCE](http://sscce.org/). 2) When in doubt, print out! A well placed call to `System.out.println(thing.toString())` can save a lot of head-aches. Alternately, use the debugger of your IDE to step through the code. – Andrew Thompson May 11 '13 at 13:08
  • Sry @Keyser, I didn't quite understand, what you mean. Would you like that I post the whole error message? – Hagi May 11 '13 at 13:08
  • Tip: Add @Keyser (or whoever) to notify them of a new comment. The `@` is important. – Andrew Thompson May 11 '13 at 13:10
  • @AndrewThompson I just wanted to make the expressions a bit shorter. – Hagi May 11 '13 at 13:28
  • 1
    Don't sacrifice clarity for the sake of a few keystrokes. Source code is intended to be human readable, so make it logical. – Andrew Thompson May 11 '13 at 13:30

1 Answers1

13

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

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

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.`

new Color((int)greyscale,(int)greyscale,(int)greyscale);
mszalbach
  • 10,612
  • 1
  • 41
  • 53