title: How to send an image over Java HTTP server
body: <p>I'm developing an HTTP server using <code>HttpServer</code> and <code>HttpHandler</code>.</p>
  
  <p>The server should response to clients with XML data or images.</p>
  
  <p>So far, I have developed <code>HttpHandler</code> implementations which respond to the clients with the XML data but I couldn't implement a <code>HttpHandler</code> which reads the image from file and send it to the client (e.g., a browser).</p>
  
  <p>The image should not be loaded fully into memory so I need some kind of streaming solution.</p>
  
  <pre><code>public class ImagesHandler implements HttpHandler {
      @Override
      public void handle(HttpExchange arg0) throws IOException {
          File file=new File("/root/images/test.gif");
          BufferedImage bufferedImage=ImageIO.read(file);
  
          WritableRaster writableRaster=bufferedImage.getRaster();
          DataBufferByte data=(DataBufferByte) writableRaster.getDataBuffer();
  
          arg0.sendResponseHeaders(200, data.getData().length);
          OutputStream outputStream=arg0.getResponseBody();
          outputStream.write(data.getData());
          outputStream.close();
      }
  }
  </code></pre>
  
  <p>This code just sends 512 bytes of data to the browser.</p>