Thursday, February 12, 2015

How to download and save image from URL

The 'javax.imageio.ImageIO' is a handy class which provides lots of utility methods related to images processing in Java. Using this class we can read and write images into disk.

In below example, We will see how to use 'javax.imageio.ImageIO' to read an image from URL and save it into different formats.

import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;

import javax.imageio.ImageIO;

/**
* This class will download the image from the specified URL and download it in
* different format.
*
* @author abdulwaheed18@gmail.com
*
*/
public class ImageDownloader {

/**
* @param args
*/
public static void main(String[] args) {

String imageUrl = "http://img.gettyimageslatam.com/public/userfiles/redesign/images/landing/home/img_entry_002.jpg";

try {
System.out.println("Downloading Image...");
URL url = new URL(imageUrl);
BufferedImage image = ImageIO.read(url);

// Save it in PNG format.
ImageIO.write(image, "png", new File("image.png"));

// Save it in JPEG format
ImageIO.write(image, "jpg", new File("image.jpg"));

// Save it in BMP format
ImageIO.write(image, "bmp", new File("image.bmp"));

// Save it in GIF format
ImageIO.write(image, "gif", new File("image.gif"));
System.out.println("Downloaded all the images");
} catch (Exception e) {
System.out.println("Error while downloading Image "
+ e.getMessage());
e.printStackTrace();
}

}
}

References :