Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store a byte array as an image file on disk?

I have a byte array representation of a Image. How to save it on disk as an image file.

I have already done this

OutputStream out = new FileOutputStream("a.jpg");
out.write(byteArray);
out.flush();
out.close();

But when I open the image by double-clicking it, it doesn't show any image.

like image 752
Yatendra Avatar asked Jan 26 '10 11:01

Yatendra


People also ask

How do I save a byte array as a picture?

Create a ByteArrayInputStream object by passing the byte array (that is to be converted) to its constructor. Read the image using the read() method of the ImageIO class (by passing the ByteArrayInputStream objects to it as a parameter). Finally, Write the image to using the write() method of the ImageIo class.

How do I write a byte array to a file?

Java – How to save byte[] to a file write is the simplest solution to save byte[] to a file. // bytes = byte[] Path path = Paths. get("/path/file"); Files. write(path, bytes);

What is byte array image?

Images are binary data - this is easily represented as byte arrays. The image in the sample is stored in the database as a BLOB - not a string or location, that is, it is binary data.

Is Blob same as byte array?

Blob simply means (Binary Large Object) and its the way database stores byte array.


1 Answers

Other than failing to use a try/finally block (at least in the code you've shown) that should be fine. (You don't need to flush an output stream if you're closing it, by the way.)

As it's not working, that suggests byteArray doesn't actually contain a JPEG-encoded image. How have you created byteArray to start with? If it's a "raw" representation, you'll probably want to encode it, e.g. using the javax.imageio package.

like image 138
Jon Skeet Avatar answered Sep 30 '22 21:09

Jon Skeet