Thursday, January 28, 2010

InputStream from URL BufferedImage

Here is how you can make an InputStream for a BufferedImage:

    URL url = new URL("http://www.google.com/intl/en_ALL/images/logo.gif");
    BufferedImage image = ImageIO.read(url);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ImageIO.write(image, "gif", os);
    InputStream is = new ByteArrayInputStream(os.toByteArray());

6 comments:

maroc said...

Thanks! This was just the code I needed to return a dynamic image to struts 2 stream type.

Nishant Modak said...

This is one more way to achieve the same thing

HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
InputStream iSReader = connection.getInputStream();
BufferedImage bufferedImage = ImageIO.read(iSReader);

as said...

I have a question!
With this method you save it on disk than you read from the disk or not?

I'm tying to upload a BufferedImage I have to a MySQL DB but to do the:

preparedStmt2.setBlob(4, image); // Image
(image on DB is type mediumBLOB)

but it only accepts image if it's type ImputStream.

Can you help?
Thanks

as said...
This comment has been removed by a blog administrator.
Russ Jackson said...

preparedStmt2.setBlob(4, is);

as said...

and to read that from the database?