Download image from web page

This example will show how to read an image such as png, gif, tiff or jpeg from a web page and save it programmatically using java, java 7 and guava. If you are looking to locate all images within a web page you could download the contents of a webpage and write a regex to find images within HTML to parse all the image locations. Once you get list of images you could perform the same operation to fetch the image. For a further challenge you could make the example more dynamic by getting the file name from the url and using it write it to the file system. If you are using a spring framework you could also leverage read a file using RestTemplate.

Setup

String IMAGE_URL = "https://www.google.com/assets/images/srpr/logo11w.png";
String IMAGE_NAME = "google-logo.png";

Using AWT

@Test
public void using_using_awt() throws IOException {

    URL imageUrlToDownload = new URL(IMAGE_URL);
    BufferedImage imageToDownload = ImageIO.read(imageUrlToDownload);

    File outputFile = new File("awt-" + IMAGE_NAME);
    ImageIO.write(imageToDownload, "png", outputFile);
}

Java 7 File I/O

@Test
public void download_image_java7() throws IOException {

    URL imageLocation = new URL(IMAGE_URL);
    ReadableByteChannel rbc = Channels.newChannel(imageLocation
            .openStream());
    FileOutputStream outputStream = new FileOutputStream("java7-"
            - IMAGE_NAME);
    outputStream.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
    outputStream.close();
}

Google Guava

@Test
public void download_image_guava() throws IOException {

    URL fetchImage = new URL(IMAGE_URL);
    byte[] imageAsArray = Resources.toByteArray(fetchImage);

    File fileToWriteTo = new File("guava-" + IMAGE_NAME);

    com.google.common.io.Files.write(imageAsArray, fileToWriteTo);
}