How do I save an image from a URL to a file?
Author: Deron Eriksson
Description: This Java tutorial shows how to download an image from a URL and save it to a file.
Tutorial created using: Windows XP || JDK 1.6.0_10 || Eclipse JEE Ganymede SR1 (Eclipse 3.4.1)


Occasionally it can be useful to have the ability to download an image from a URL programmatically and save it as a file. A standard way to do this in JavaSW is to obtain an input stream to read from a URL and then write this to an output stream associated with a file.

The SaveImageFromUrl class demonstrates this technique. It obtains a URL object for an image and then obtains an input stream to this image. It creates an output stream to a file via FileOutputStream. Using standard Java stream handling, the input stream is read in chunks via the while loop, and the bytes are written to the output stream.

SaveImageFromUrl.java

package com.cakes;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

public class SaveImageFromUrl {

	public static void main(String[] args) throws Exception {
		String imageUrl = "http://www.avajava.com/images/avajavalogo.jpg";
		String destinationFile = "image.jpg";

		saveImage(imageUrl, destinationFile);
	}

	public static void saveImage(String imageUrl, String destinationFile) throws IOException {
		URL url = new URL(imageUrl);
		InputStream is = url.openStream();
		OutputStream os = new FileOutputStream(destinationFile);

		byte[] b = new byte[2048];
		int length;

		while ((length = is.read(b)) != -1) {
			os.write(b, 0, length);
		}

		is.close();
		os.close();
	}

}