Read And Write Images In Java

To read and write image files from local disk or from any URL, javax.imageio.ImageIO class is used. javax.imageio.ImageIO is a final class with some static methods which are useful for image processing.

Java Program To Read & Write Image From Local Disc:-

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 & Write Image 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");

    }

}
Author: Fabian Ros
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments