Thursday, July 10, 2008

A Note on Downloading Images to a Java Client via HTTP requests

I've been working on a little Java client to grab some internet data and process it into a nice little picture. In order to do this, I needed to be able to download pictures from an HTTP request into a BufferedImage.

When initially trying to find a way to do this, Google only gave me worthless pages about using the URLConnection.getContent() method, or saving to a file and loading that file, or a number of worthless suggestions. The simplest way to do it is to use the URLConnection as normal, but then to stick the InputStream into the IOImage.read() method, as follows:


URL url = new URL(urlstring);
URLConnection uc = url.openConnection();

InputStream content = (InputStream) uc.getInputStream();
BufferedImage image = ImageIO.read(content);


Be sure to wrap everything in the proper try/catch blocks and you are golden. Bonus points for starting a thread and running it in the background and notifying your canvas when it is ready. No sense in blocking your UI!

I also note that it has been 16 months since I used this blog, but this post serves an important internet service to those who don't program with Java as frequently as I --I mean they-- should.