title: java servlet: get image from url and display it
body: <p>How would I go about grabbing an image from a URL, and then displaying it... much like a proxy would?</p>
  
  <p>I figured that I would need to first get the image to a filestream and then output the file.  Here's the code:</p>
  
  <pre><code>    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
          // temporarily hard-code the image
          String imageUrlString = "http://i.imgur.com/3lQAD2E.jpg";
  
           // Read the image ...
          URL urlConn = new URL(imageUrlString);
          InputStream inputStream      = urlConn.openStream();
          ByteArrayOutputStream output = new ByteArrayOutputStream();
          byte [] buffer               = new byte[ 1024 ];
  
          int n = 0;
          while (-1 != (n = inputStream.read(buffer))) {
             output.write(buffer, 0, n);
          }
          inputStream.close();
  
          // Here's the content of the image...
          byte [] data = output.toByteArray();
  
          PrintWriter out = response.getWriter();
          out.print(data);     
      }  
  </code></pre>
  
  <p>However, the return is just a broken image file.</p>