Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 700
Jochem Gruter Avatar asked Jan 19 '13 16:01

Jochem Gruter


1 Answers

int[] bitMasks = new int[]{0xFF0000, 0xFF00, 0xFF, 0xFF000000};
SinglePixelPackedSampleModel sm = new SinglePixelPackedSampleModel(
        DataBuffer.TYPE_INT, width, height, bitMasks);
DataBufferInt db = new DataBufferInt(pixels, pixels.length);
WritableRaster wr = Raster.createWritableRaster(sm, db, new Point());
BufferedImage image = new BufferedImage(ColorModel.getRGBdefault(), wr, false, null);
like image 144
Yu Kobayashi Avatar answered Oct 13 '22 11:10

Yu Kobayashi