2

I need to obtain the pixel data from a BufferedImage so I can recreate the image from the data. I looked into Raster, but that did not seem to contain the information I need. How can I obtain data from a BufferedImage so I can recreate the image without needing the original file?

skynet
  • 9,898
  • 5
  • 43
  • 52
Charsmud
  • 183
  • 1
  • 4
  • 19
  • What do you mean with recreate without the original file? – arynaq Oct 27 '13 at 21:32
  • I want to obtain the image's data (pixel color, size, etc) and save and recreate the image from that data. – Charsmud Oct 27 '13 at 22:03
  • 1
    [this example](http://arashmd.blogspot.com/2013/07/java-thread-example.html#lc) or [this](http://arashmd.blogspot.com/2013/07/java-thread-example.html#rccig) may help. –  Oct 27 '13 at 22:14
  • Do you need pixel access, to manipulate the image data, or is the idea just to avoid needing the original fileIs it a requirement to do it in memory, or is it okay to store to (another) file? – Harald K Oct 28 '13 at 08:36

1 Answers1

0

You should check out the answers to this question

Java - get pixel array from image

One way to do it is to use

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(originalImage, "jpg", baos);
baos.flush();
byte[] imageBytes = baos.toByteArray();
baos.close();

Now when you want to create a new BufferedImage from the data you use

ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes);
BufferedImage newImage = null;
try {
    newImage = ImageIO.read(bais);
} catch (IOException e) {
    // handle exception
}
Community
  • 1
  • 1
skynet
  • 9,898
  • 5
  • 43
  • 52
  • How do I apply that pixel data to another BufferedImage? – Charsmud Oct 27 '13 at 23:27
  • @Charsmud Good question! I have added instructions in the answer. – skynet Oct 27 '13 at 23:32
  • @Craigy You can not read a byte array back, using ImageIO, like in your example. ImageIO reads images stored in a file format. Although your code compiles, `newImage` will be `null`. You need to recreate using `new BufferedImage(colormodel, raster, colormodel.isAlphaPremultiplied(), null)` (ie, you need to know the `ColorModel` as well as the raster). – Harald K Oct 28 '13 at 08:34
  • @haraldK you're right. I have updated the answer so that the image can be recreated. – skynet Oct 28 '13 at 11:39