Reputation: 1132
I have the following code, that transforms an Image into a byte[]:
BufferedImage image = ImageIO.read(new File("Path/To/Custom/image.jpg"));
ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
ImageIO.write(image, "jpg", baos);
byte[] imageBytes = baos.toByteArray();
This code works totally fine, at least I get a byte array containing different values. But now comes the difficult part: The byte[] has to be reconstructed into am image again. The following code does not work, ImageIO.read(...)
returns null. I read the documentation, but still I can not find out what to change so that the code functions in the way I want it to.
ByteArrayInputStream ba = new ByteArrayInputStream(imageBytes);
BufferedImage image = ImageIO.read(ba);
//image is always null, no matter what the stream or the byte values are.
Upvotes: 1
Views: 2414
Reputation: 385
Try reading an ByteArrayInputStream
on ImageIO.read()
not an ByteArrayOutputstream
.
Upvotes: 1
Reputation: 554
import java.io.ByteArrayOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class ByteArrayToImage {
public static void main(String args[]) throws Exception {
BufferedImage bImage = ImageIO.read(new File("sample.jpg"));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(bImage, "jpg", bos );
byte [] data = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(data);
BufferedImage bImage2 = ImageIO.read(bis);
ImageIO.write(bImage2, "jpg", new File("output.jpg") );
System.out.println("image created");
}
}
Modify this to your needs.
Upvotes: 3