title: JSP/Servlet : How to Read an image via URL and render it on a JSP page (image URL is not public)
body: <p>what's the best approach to read an image via URL and render it on a JSP page?</p>
  
  <p>so far, I've coded two JSP pages.</p>
  
  <p>EDIT START:</p>
  
  <pre><code> *Experimental: Obviously the ImageServ will be a servlet, not a jsp. 
  </code></pre>
  
  <p>EDIT END:</p>
  
  <pre><code>index.jsp
  
  &lt;%page ....
  &lt;html&gt;
  ......
  &lt;img src="ImageServ.jsp?url=http://serveripaddress/folder/image.jpg" /&gt;
  .....
  
  
  ImageServ.jsp
  &lt;%@page import="javax.imageio.ImageIO"%&gt;
  &lt;%@page import="java.net.URL"%&gt;
  &lt;%@page import="java.io.*, java.awt.*, java.awt.image.*,com.sun.image.codec.jpeg.*" %&gt;
  &lt;%
      try {
          String urlStr = "";
          if(request.getParameter("url") != null)
          {
              urlStr = request.getParameter("url");
              URL url = new URL(urlStr);
              BufferedImage img = null;
              try{
                      img = ImageIO.read(url);
                      out.println(" READ SUCCESS" + "&lt;br&gt;");
              }catch(Exception e) {
                      out.println("READ ERROR "  + "&lt;br&gt;");
                      e.printStackTrace(new PrintWriter(out));
              }
  
              try {
                      response.setContentType("image/jpeg");
                      JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response.getOutputStream());
                      encoder.encode(img);
                   }catch(Exception ee) {
                              response.setContentType("text/html");
                              out.println("ENCODING ERROR "  + "&lt;br&gt;");
                              ee.printStackTrace(new PrintWriter(out));
              }
        }
  
      } catch (Exception e) {
          e.printStackTrace(new PrintWriter(out));
      }
  %&gt;
  </code></pre>
  
  <p>But this  doesn't seem to be working:
  all the time i see this error:</p>
  
  <pre><code>READ SUCCESS
  ENCODING ERROR
  java.io.IOException: reading encoded JPEG Stream 
      at sun.awt.image.codec.JPEGImageEncoderImpl.writeJPEGStream(Native Method)
      at sun.awt.image.codec.JPEGImageEncoderImpl.encode(JPEGImageEncoderImpl.java:476)
      at sun.awt.image.codec.JPEGImageEncoderImpl.encode(JPEGImageEncoderImpl.java:228)
  </code></pre>
  
  <p>Any ideas on how to get this working???</p>