Image Byte Array Conversion using Java

Hello everyone, In this post I am attaching the simple program about Image Byte Array Conversion using Java. The example program has been tested and output is shared in the same post.

ImageConversion.java

The following program about Image Byte Array Conversion using Java program. The java.util.ArrayList also some of the API`s are used from java.io package. such as File, FileInputStream, FileOutputStream and etc.. you can find the output below of the program.

package com.javatraineronline;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class ImageConversion {

	// Converting Image to Byte Array(ArrayList)
	public List<Integer> convertImageToList(String inputFilePath) {
		
		List<Integer> list = new ArrayList<Integer>();
		
		if(inputFilePath !=  null && !"".equals(inputFilePath)) {
		
			File inputFile = new File(inputFilePath);
			
			try {
				
				FileInputStream fis = new FileInputStream(inputFile);
				
				int data = fis.read();
				
				while(data != -1) {
					
					list.add(data);
					
					data = fis.read();
				}
				
				fis.close();
				
			} catch (FileNotFoundException e) {
				
				System.out.println(e.getMessage());
			} catch (IOException e) {
				
				System.out.println(e.getMessage());
			}
		}
		
		System.out.println("Image Converted as List Object");
		
		return list;
	}
	
	// Convert Byte Array to Image
	public void convertListToImage(List<Integer> list, String outputFilePath) {
		
		
		if((list != null && list.size() > 0) && (outputFilePath != null && !"".equals(outputFilePath))) {	
			
			File outFile = new File(outputFilePath);
			
			try {
				
				FileOutputStream fos = new FileOutputStream(outFile);
				
				for(Integer i : list) {
					
					fos.write(i);
				}
				
				fos.close();
				
			} catch (FileNotFoundException e) {
				
				System.out.println(e.getMessage());
			} catch (IOException e) {
				
				System.out.println(e.getMessage());
			}
			
			System.out.println("List Object Converted as Image");
		}
	}
	
	
	public static void main(String[] args) throws IOException {
		
		ImageConversion conversion = new ImageConversion();
		
		String inputFilePath = "in.jpg"; // Change your image path accordingly
		String outputFilePath = "out.jpg";
		
		List<Integer> list = conversion.convertImageToList(inputFilePath);
		
		conversion.convertListToImage(list, outputFilePath);
		
		System.out.println("All the Conversions happened successfully check your file system.");
	}
}

Output

——————

Image Converted as List Object
List Object Converted as Image
All the Conversions happened successfully check your file system.