The conversion from byte[] to BufferedImage is involved the use of InputStream and ImageIO.read as following :

InputStream in = new ByteArrayInputStream(imageInByte);
BufferedImage bImageFromConvert = ImageIO.read(in);

The following example will read an image file named “darksouls.jpg“, convert it into byte array, and then reuse the converted byte array, and convert it back to a new BufferedImage, and save it back into a new name “new-darksouls.jpg“.

package com.mkyong.image;
 
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
 
public class ImageTest {
 
	public static void main(String[] args) {
 
		try {
 
			byte[] imageInByte;
			BufferedImage originalImage = ImageIO.read(new File(
					"c:/darksouls.jpg"));
 
			// convert BufferedImage to byte array
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ImageIO.write(originalImage, "jpg", baos);
			baos.flush();
			imageInByte = baos.toByteArray();
			baos.close();
 
			// convert byte array back to BufferedImage
			InputStream in = new ByteArrayInputStream(imageInByte);
			BufferedImage bImageFromConvert = ImageIO.read(in);
 
			ImageIO.write(bImageFromConvert, "jpg", new File(
					"c:/new-darksouls.jpg"));
 
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}
}
Tags :
Founder of Mkyong.com, love Java and open source stuffs. Follow him on Twitter, or befriend him on Facebook or Google Plus.
Here are some of my recommended Books

Related Posts

Popular Posts