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:

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

    ReplyDelete
  2. 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);

    ReplyDelete
  3. 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

    ReplyDelete
  4. This comment has been removed by a blog administrator.

    ReplyDelete
  5. and to read that from the database?

    ReplyDelete