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
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
{
int width = 963 ;
int height = 640 ;
BufferedImage image = null ;
try {
File input_file = new File(
"C:/Users/hp/Desktop/Image Processing in Java/gfg-logo.png" );
image = new BufferedImage(
width, height, BufferedImage.TYPE_INT_ARGB);
image = ImageIO.read(input_file);
System.out.println( "Reading complete." );
}
catch (IOException e) {
System.out.println( "Error: " + e);
}
try {
File output_file = new File(
"C:/Users/hp/Desktop/Image Processing in Java/gfg.png" );
ImageIO.write(image, "png" , output_file);
System.out.println( "Writing complete." );
}
catch (IOException e) {
System.out.println( "Error: " + e);
}
}
}
|
Output –
Note: This code will not run on online IDE as it needs an image on disk.
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
14 Nov, 2021
Like Article
Save Article