java imageio write byte array

Tutorialspoint
Home
Q/A
Tools
Coding Ground
Current Affairs
UPSC Notes
Online Tutors
Code Examples
Whiteboard
Net Meeting
Articles

Tutorialspoint

Library
Videos
eBooks

Register
Login

  • Library
  • Videos
  • eBooks
  • Register
    Login

  • Comments
  • Edit Question
  • Edit Categories

How to convert Byte Array to Image in java?

How to convert Byte Array to Image in java?

  Follow
Answer
4679

0
0

1 Answer

V Jyothi

V Jyothi
,
662 Views

Java provides ImageIO class for reading and writing an image. To convert a byte array to an image.

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

Example

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");
   

Output

image created