In this article, we will learn how to read and write image objects using Java.
Reading Image:
To read an image, first create a java.io.File object.
File file = new File("location of image");
Create a byte array. This array will store image data, byte by byte. The size of this byte array will be the length of input file. i.e, file.length();
long size = file.length();
byte[] bytes = new byte[(int)size];
Create a FileInputStream object which will take file as a parameter. This object will read the image byte by byte and store it in the bytes array.
FileInputStream fis = new FileInputStream(file);
Read the bytes from FileInputStream object into the bytes array.
fis.read(bytes);
Close the FileInputStream
fis.close();
Complete Java code:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class Example{
public static void main(String[] args) throws IOException{
File file = new File("Image location");
FileInputStream in = new FileInputStream(file);
long size = file.length();
byte[] temp = new byte[(int)size];
in.read(temp);
in.close();
}
}
Writing Image to File :
We have loaded our image in the form of bytes array. This byte array can be written to file using FileOutputStream.
Create the file object for the new file.
File file = new File("new File location");
Create a FileOutputStream object and pass this file to it.
FileOutputStream fos = new FileOutputStream(file);
We will use bufferedOutputStream to wrap fos object as it is more efficient.
BufferedOutputStream bos = new BufferedOutputStream(fos);
Finally create a DataOutputStream object and pass bos to it.
DataOutputStream dos = new DataOutputStream(bos);
write the bytes array to dos and close it.
dos.write(bytes);
dos.close();
Complete java code to write bytes array as new image file:
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class temp{
public static void main(String[] args) throws IOException{
File file = new File("img.jpg"); // img.jpg can be any image file
FileInputStream in = new FileInputStream(file);
long size = file.length();
byte[] temp = new byte[(int)size];
in.read(temp);
in.close();
// The img.jpg image data will be written in a new image File named "output.jpg"
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(new File("output.jpg"))));
dos.write(temp);
dos.close();
}
}