2014-10-30 57 views
2

我將如何去從URL中抓取圖像,然後顯示它...很像代理服務器?java servlet:從url獲取圖像並顯示它

我想我需要先將圖像傳輸到文件流然後輸出文件。這裏的代碼:

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);  
    } 

但是,返回只是一個破碎的圖像文件。

回答

相關問題