TorchTT
TorchTT

Reputation: 132

Incorrect conversion from array to BufferedImage

Image converted to RGB grayscale.
Next, Grayscale-image is translated into an array, which are performed to define a transformation. As a result, the array consists of "0" and "255".

Then, I need to turn this array into BufferedImage.

I used the code:

public static BufferedImage getImageFromArray(int pixelsMain[][], int width, int height) throws IOException {

        int pixels[] = new int[320*240];

        for(int i=0, numb=0; i<pixelsMain.length; i++)
            for(int j=0; j<pixelsMain[i].length; j++){
                pixels[numb]=pixelsMain[i][j];
                numb++;
            }

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
        WritableRaster raster = (WritableRaster) image.getData();
        raster.setPixels(0,0,width,height,pixels);
        try {
            ImageIO.write(image, "bmp", new FileOutputStream("[path]"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }

However, after performing the method - all the values ​​of "255" converted to "-1".

As a result, the image is completely black.

Can you please tell how to solve the problem?

Upvotes: 3

Views: 603

Answers (1)

Gene
Gene

Reputation: 46960

Use image.getRaster() instead of (WritableRaster)image.getData(). The latter is making a copy, so changing it has no effect.

Upvotes: 4

Related Questions