Convert image to byte array

Convert image to byte array : Whenever we have to save image somewhere either on disk or database it is required to convert image to byte array and save it. Below sample program which shows how to convert image to byte array:

package com.image;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

public class TestImage {

    public static void main(String[] args) {

	ByteArrayOutputStream baos = null;
	FileOutputStream fileOuputStream = null;

	try {
	    BufferedImage originalImage = ImageIO.read(new File(
		    "C:/Image/Small_Red_Rose.JPG"));

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

	    // convert array of bytes into modified file again
	   fileOuputStream = new FileOutputStream(
		    "C:/image/Converted_Small_Red_Rose.JPG");
	    fileOuputStream.write(imageInByte);	    

	    System.out.println("Conversion completed");

	} catch (IOException e) {
	    e.printStackTrace();
	}finally{
	    try {
		baos.close();
		fileOuputStream.close();
	    } catch (IOException e) {
		e.printStackTrace();
	    } 

	}

    }

}

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *