Java implements a particular type of object called a BufferedImage for images in Java. A BufferedImage can be read from several distinct image types (i.e., BMP, HEIC, etc.). Not all of these are backed by ImageIO itself, but there are plugins to extend ImageIO and other libraries such as Apache Imaging and JDeli.
In Java itself, all the complexity of various image types is hidden, and we only work on BufferedImage. Java provides immediate access to the image pixels and color information and allows conversions and image processing.
Classes Required to Perform the Read and Write Operations:
1. java.io.File: To read and write an image file, we must import the File class. This class represents file and directory path names in general.
2. java.io.IOException: To handle errors, we use the IOException class.
3. java.awt.image.BufferedImage: To hold the image, we create the BufferedImage object; we use BufferedImage class. This object is used to store an image in RAM.
4. javax.imageio.ImageIO: To perform the image read-write operation, we will import the ImageIO class. This class has static methods to read and write an image.
// Java program to demonstrate read and write of image import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class MyImage {
public static void main(String args[])
throws IOException
{
// width of the image
int width = 963 ;
// height of the image
int height = 640 ;
// For storing image in RAM
BufferedImage image = null ;
// READ IMAGE
try {
File input_file = new File(
"C:/Users/hp/Desktop/Image Processing in Java/gfg-logo.png" );
// image file path create an object of
// BufferedImage type and pass as parameter the
// width, height and image int
// type. TYPE_INT_ARGB means that we are
// representing the Alpha , Red, Green and Blue
// component of the image pixel using 8 bit
// integer value.
image = new BufferedImage(
width, height, BufferedImage.TYPE_INT_ARGB);
// Reading input file
image = ImageIO.read(input_file);
System.out.println( "Reading complete." );
}
catch (IOException e) {
System.out.println( "Error: " + e);
}
// WRITE IMAGE
try {
// Output file path
File output_file = new File(
"C:/Users/hp/Desktop/Image Processing in Java/gfg.png" );
// Writing to file taking type and path as
ImageIO.write(image, "png" , output_file);
System.out.println( "Writing complete." );
}
catch (IOException e) {
System.out.println( "Error: " + e);
}
} // main() ends here
} // class ends here
|
Output –
Note: This code will not run on online IDE as it needs an image on disk.