Writing an Image file in Java is very common scenario and in this article we will see a new way to write images into file in Java. javax.imageio.ImageIO is a utility class which provides lots of utility method related to images processing in Java. Most common of them is reading form image file and writing images to file in java. You can write any of .jpg, .png, .bmp or .gif images to file in Java. Just like writing, reading is also seamless with ImageIO and you can read BufferedImage directly from URL. Reading Images are little different than reading text or binary file in Java as they they are associated with different format. Though you can still use getClass().getResourceAsStream() approach for loading images.
Image Read Write Example using ImageIO
Code Example Image Read and Write in Java
Here is complete Code Example of reading and writing Images to file in Java, we will first read the image and than write the same image in different format e.g. JPG, PNG and BMP into disk.
In this code Exmaple of javax.imageio.ImageIO class we will see:
How to read Buffered Image in Java from File or URL
How to write JPG images to file in Java
How to write PNG images to file in Java
How to write BMP images to file in Java
How to write GIF images to file in Java
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
public class ImageIOExample {
public static void main( String[] args ){
BufferedImage image = null;
try {
//you can either use URL or File for reading image using ImageIO
File imagefile = new File("C://Documents and Settings/Javin/My Documents/My Pictures/loan.PNG");
image = ImageIO.read(imagefile);
//ImageIO Image write Example in Java
ImageIO.write(image, "jpg",new File("C:\\home_loan.jpg"));
ImageIO.write(image, "bmp",new File("C:\\credit_card_loan.bmp"));
ImageIO.write(image, "gif",new File("C:\\personal_loan.gif"));
ImageIO.write(image, "png",new File("C:\\auto_loan.png"));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Success");
}
}
Apart from seemless support of reading and writing images in Java, ImageIO class also contains lot of other utility methods for locating ImageReaders and ImageWriters and performing encoding and decoding.
That's all on this Reading and Writing Image File in Java using javax.imageio.ImageIO. Let me know if you face any issue while trying these examples of ImageIO.
Related Java Tutorials
Tidak ada komentar:
Posting Komentar