How to load an image from a URL in java
Assuming you want to load the image from the URL into memory in order to display or manipulate it:
try { URL imageUrl = new URL("http//example/image.jpg"); InputStream in = imageUrl.openStream(); BufferedImage image = ImageIO.read(in); in.close(); } catch (IOException ioe) { //log the error } |
Loading an image from a URL is as simple as that. Now you’ve got a BufferedImage
.
It can be even simpler, and if all you are doing is cropping or resizing the image, you may be interested in a little java image utility I wrote. Using my ImageLoader
and Image
classes, the code would look like:
try { Image image = ImageLoader.fromUrl("http//example/image.jpg"); } catch (IOException ioe) { //log the error } |
The Image
class is a wrapper on a BufferedImage
and provides some useful methods for cropping, resizing, and writing (saving) the image. Let me know in the comments below if you’ve found this helpful.