Reading and writing images in Java
To read and write image files from local disk or any URL, use javax.imageio.ImageIO class. javax.imageio.ImageIO is a final class with some static methods useful for image processing.
Java program to read and write images from local disk:-
import java. awt. image. BufferedImage ;
import java. io. File ;
import java. io. IOException ;
import javax. imageio. ImageIO ;
public class ReadAndWriteImage {
public static void main ( String [ ] args) {
File file = new File ( "D:/apple.jpg" ) ;
BufferedImage image = null ;
try {
image = ImageIO . read ( file) ;
ImageIO . write ( image, "jpg" , new File ( "D:/apple.jpg" ) ) ;
ImageIO . write ( image, "png" , new File ( "D:/apple.png" ) ) ;
ImageIO . write ( image, "gif" , new File ( "D:/apple.gif" ) ) ;
ImageIO . write ( image, "bmp" , new File ( "D:/apple.bmp" ) ) ; }
catch ( IOException e)
{
e. printStackTrace ( ) ;
}
System . out. println ( "Here it is" ) ;
}
}
Java program to read and write images from URL:-
import java. awt. image. BufferedImage ;
import java. io. File ;
import java. io. IOException ;
import java. net. MalformedURLException ;
import java. net. URL ;
import javax. imageio. ImageIO ;
public class ReadAndWriteImage
{
public static void main ( String [ ] args) {
URL url = null ;
BufferedImage image = null ;
try {
url = new URL ( "https://code-projects.org/fimg.png" ) ;
}
catch ( MalformedURLException e1)
{
e1. printStackTrace ( ) ;
}
try
{
image = ImageIO . read ( url) ;
ImageIO . write ( image, "jpg" , new File ( "D:/apple.jpg" ) ) ;
ImageIO . write ( image, "png" , new File ( "D:/apple.png" ) ) ;
ImageIO . write ( image, "gif" , new File ( "D:/apple.gif" ) ) ;
ImageIO . write ( image, "bmp" , new File ( "D:/apple.bmp" ) ) ;
}
catch ( IOException e)
{
e. printStackTrace ( ) ;
}
System . out. println ( "Here it is" ) ;
}
}