Search code examples
javabufferedimagepixel

int array to BufferedImage


I'm making with the Robot class a printscreen and I convert the BufferedImage into an int array. Then I want to convert the int array back to a bufferedimage but that gives an error. This is my code:

Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
BufferedImage printscreen = robot.createScreenCapture(new Rectangle(screen));
int[] pixels = ((DataBufferInt) printscreen.getRaster().getDataBuffer()).getData();

BufferedImage image = new BufferedImage(screen.width, screen.height, BufferedImage.TYPE_INT_RGB);
WritableRaster raster = (WritableRaster) image.getRaster();
raster.setPixels(0, 0, screen.width, screen.height, pixels);

But I get the error: ArrayIndexOutOfBoundsException: 2073600 but why?

I'm getting the exception on this line:

raster.setPixels(0, 0, screen.width, screen.height, pixels);

EDIT: It is working if I change the second bufferedimage type to TYPE_BYTE_GRAY.


Solution

  • Changed to:

    getRaster().getPixels(0, 0, screen.width, screen.height, pixels)
    

    and it works! Thanks for help anyway