Question

I want to load an image to resize it to 100x100 to reshape it in 1x100000 and save it in an txt file. So I read it in bufferedImage, I resize it to 100x100. The next steps for reshaping it and save the double values of it is what I am looking for:

            File img = new File(train_path + fileNames.get(i) + "/" + imageNames.get(i).get(j));
            BufferedImage in = ImageIO.read(img);
            BufferedImage newImage = new BufferedImage(in.getWidth(), in.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
            Graphics2D g = newImage.createGraphics();
            g.drawImage(in, 0, 0, null);
            g.dispose();

            BufferedImage newImg = new BufferedImage(100, 100, BufferedImage.TYPE_BYTE_GRAY);

            Graphics gr = newImg.createGraphics();
            gr.drawImage(newImage, 0, 0, 100, 100, null);
            gr.dispose();
            System.out.println(newImage.getHeight()+ " "+ newImage.getWidth());
            System.out.println(newImg.getHeight()+ " "+ newImg.getWidth());
Was it helpful?

Solution

You can get an array of int from the initial image:

int[] pixels = newImage.getRGB(0, 0, 100, 100, null, 0, 100);

which means get RGB values from (0,0) to (100,100) in a new array, starting from index 0, offsetting index for each line of 100.

Then for each int in pixels, the grayscale value is given by:

int gray = pixels[i] & 0xFF;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top