Convert image to BufferedImage

Convert image to BufferedImage : Sample image we are using is JPG image which we are reading for local drive then convert it to byte array. Once it’s converted to byte array again 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 *