Convert image to ByteArrayOutputStream : Sample image we are using is JPG image which we are reading for local drive then convert image to ByteArrayOutputStream. We are creating byte array from ByteArrayOutputStream then we are writing back to file and create copy of the image. Please have sample java program:

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 *