Javaservlet:从url获取图像并显示它
我如何从URL抓取图像,然后显示它。。。就像代理一样 我想我需要首先将图像获取到文件流,然后输出文件。代码如下:Javaservlet:从url获取图像并显示它,java,servlets,Java,Servlets,我如何从URL抓取图像,然后显示它。。。就像代理一样 我想我需要首先将图像获取到文件流,然后输出文件。代码如下: protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // temporarily hard-code the image String imageUrlStri
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);
}
但是,返回的只是一个损坏的图像文件。您应该使用而不是编写器。作者处理字符数据。此外,您可能希望了解回复