2014-10-30 58 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);  
    } 

但是,返回只是一个破碎的图像文件。

回答

相关问题