Save Image data

I want to save an image data into a file via FileOutputStream and restore back as needed through FileInputStream, such as :

  Save :

  int[] data;
  BufferedImage.getRGB(0, 0, w,h, data, 0, w);

  Save data via FileOutputStream

  Restore:

  Get  data back via FileInputStream
  BufferedImage.setRGB(0, 0, w,h, data, 0, w);

The problem is both FileInputStream and FileOutputStream require byte[] not int[]. How can I convert int[] to bye[] and visa efficiently or Java has something allow you to save buffered image data into a file and restore back as needed ?

Jay

Have a look at the API class ImageIO, it have all you need.

Cheers,
Mikael Grev

Thanks for the response. I’m not looking for saving image data as any kind of image format as described in imageIO. I just need to save a buffered image data using simple IO and restore back if needed. By doing this way, I can get much better IO performance when I create multiple levels of undo image on disk.

Basically, I can undo an image changes by using the following sequence :

//copy image original data into int[] data

BufferedImage.getRGB(0, 0, w,h, data, 0, w);

//Make some changes to bufferedImage

//undo the changes by restoring back data
BufferedImage.setRGB(0, 0, w,h, data, 0, w);

This works fine except that I have to use a lot of memory to store multiple undo data for creating multiple undo. In order to avoid that, I want to save data array not the entire image on disk. I tried with BufferedInputStream to read back the saved data as int type but it appears that the data was changed when it was saved using BufferedOutputStream.

Does anyone know a better way to create multiple undo for a large image without consuming too much memory while maintaining relatively good performance ?

Jay

Photoshop has always used huge amounts of memory for images. The rule of thumb was, image mem size x 5 = prefered free memory.

Back in the days when I had a 64meg machine and I tried working on 5-10 meg images, the hard drive got quite a work out as data was swapped in and out.

Wouldnt you get better performance by not accessing the hard drive. As long as the machine has 256+ meg I dont think you would have too much trouble storing the undo in memory. Most paint programs also allow the user to set the level of undo. Even Photoshop doesnt have an unlimited undo.

You can also improve your memory usage by only saving the changes.

If you want, you can get bytes out of the image instead of ints. Use:


BufferedImage image = ...
byte data[] = (byte[]) image.getRaster().getDataElements(0, 0, image.getWidth(), image.getHeight(), null);