Search code examples
javaurlbytearrayinputstream

Read the binary image data from a URL into a ByteArrayInputStream from HttpUrlConnect::URL


I'm trying to pull the image from a URL and read it directly into a ByteArrayInputStream. I found one way of doing it, but it requires an image type, and there will be various image types, so I'd like to find a simple way to just read the binary data right in.

Here is my latest attempt. I'm using a BufferedImage, which I don't think is necessary.

URL url = new URL("http://hobbylesson.com/wp-content/uploads/2015/04/Simple-Acrylic-Painting-Ideas00005.jpg");

//Read in the image
BufferedImage image = ImageIO.read(url);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);
is = new ByteArrayInputStream(baos.toByteArray());

Solution

  • Here's the solution I found to work. Thanks for the two approaches above. I'd rather avoid external libraries, but because the environment is a real pain. Similar, I should have access to Java 9 and transferTo(), but that's not working.

    This answerer was also helpful: Convert InputStream(Image) to ByteArrayInputStream

    URL url = new URL("http://hobbylesson.com/wp-content/uploads/2015/04/Simple-Acrylic-Painting-Ideas00005.jpg");
            
    InputStream source = url.openStream();
    byte[] buf = new byte[8192]; 
    int bytesRead = 0;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    while((bytesRead = source.read(buf)) != -1) {
         baos.write(buf, 0, bytesRead);
    }
    is = new ByteArrayInputStream(baos.toByteArray());