Category Archives: Java Code

read java image from url and save to byte array

Howto create an image object from url (file, http, etc.) and the basics to get it saved to stream – here to byte array

    package dummy;

    import java.awt.image.BufferedImage;
    import java.io.ByteArrayOutputStream;
    import java.net.URL;
    import javax.imageio.ImageIO;

    public class ImageReader {

        public void main(String[] args) throws Exception {

            URL url = new URL("http://www.othiemann.info/wp-content/uploads/2013/09/IMG_06392.jpg");

            // read image direct from url
            BufferedImage image = ImageIO.read(url);

            // write image to outputstream
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", baos);
            baos.flush();

            // get bytes
            byte[] imageBytes = baos.toByteArray();
        }
    }