-1

I'm looping through an image with X and Y coordinates. However, I can only set an sRGB value using the method: image.setRGB(int x, int y, int rgb);

I want to set a custom RED, GREEN and BLUE values to the current X and Y coordinates. The new RGB values are in this case the average of the original RGB values.

The result I get is a blue image instead of greyscale.

for (int y = 0; y < imageInput.getHeight(); y++) {
        for (int x = 0; x < imageInput.getWidth(); x++) {
            int clr = imageInput.getRGB(x, y);
            Color color = new Color(clr);
            int red = color.getRed();
            int green = color.getGreen();
            int blue = color.getBlue();

            int sumRGB = red + green + blue;
            int avg = sumRGB/3;
            System.out.println("sRGB: " + clr);
            System.out.println("Input Image: x= " + x + " y= " + y + " [" + red + "," + green + "," + blue + "]");
            System.out.println("Avg RGB: " + avg);

            imageCopy.setRGB(x, y, avg);
            int clrCopy = imageCopy.getRGB(x, y);
            color = new Color(clrCopy);

            red = color.getRed();
            green = color.getGreen();
            blue = color.getBlue();
            System.out.println("Output Image: x= " + x + " y= " + y + " [" + red + "," + green + "," + blue + "]\n");
        }
    }
Guy BD
  • 69
  • 1
  • 3
  • 10
  • 1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) One way to get image(s) for an example is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). – Andrew Thompson Jun 11 '18 at 05:51
  • For much better performance (skip color model conversions, etc), see the second half of this answer: https://stackoverflow.com/a/49650210/1052284 – Mark Jeronimus Jun 11 '18 at 12:02

1 Answers1

1

You could write

Color greyScaleColor = new Color(avg, avg, avg);
int rgbValueForGrey = greyScaleColor.getRGB();

This will give you the int value that you need to set in imageCopy.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110