1

I have a task to read grayscale image in png format to 2d array, and make some arithmetic operations on each pixel. I wrote some code which read my image and transform it to 2d array, but in the result my image is more dark even if I don't change anything yet. My code:

            BufferedImage image = ImageIO.read(new File(IMAGE_PATH + "gray/squirrel.png"));

            int width = image.getWidth();
            int height = image.getHeight();

            int[][] imageData = new int[width][height];
            for(int i = 0; i < width ; ++i){
                for(int j = 0 ; j < height ; ++j){
                    Color color = new Color(image.getRGB(i,j));
                    imageData[i][j] = (color.getRed() + color.getGreen() + color.getBlue()) / 3;
                }
            }

            BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);

            for (int x = 0; x < width ; x++) {
                for (int y = 0; y < height; y++) {
                    newImage.setRGB(x, y, imageData[x][y]);
                }
            }

            File outputfile = new File("image.png");
            ImageIO.write(newImage, "png", outputfile);

Image

ilovespring
  • 73
  • 1
  • 4
  • 2
    You are making average of 0-255 in the first for loop. In the second loop, you write color 0-255 as RGB (RGB is in range 0-0xFFFFFF), and then it's converted into grayscale again – Ecto Apr 29 '20 at 17:07
  • @Ecto make it an answer. I will delete mine and upvote yours. You are right. – Axel Apr 29 '20 at 17:27
  • @ilovespring: when your code works, the next step is to apply the correct weights to the different colours as described in this question: https://stackoverflow.com/questions/687261/converting-rgb-to-grayscale-intensity – Axel Apr 29 '20 at 17:31
  • @Ecto Thank you, it works :) I have one more question - if I have three int values for some pixel of my color image, for example (152, 120, 240) - how can I set pixel in BufferedImage? Method setRgb require one int value for rgb - should i merge this three value for one or something? – ilovespring Apr 29 '20 at 18:10
  • 1
    @ilovespring use new Color(r, g, b).getRGB(); – Ecto Apr 29 '20 at 18:14
  • @Ecto now I love you. Thanks ! – ilovespring Apr 29 '20 at 18:14
  • @ilovespring if you want a one liner, but perhaps less maintainable code, you can also do a bitwise (r<<16 | g << 8 | b). – John C Apr 29 '20 at 19:56

0 Answers0