如何从网址在网页上显示图像

时间:2014-05-12 18:47:13

标签: java image servlets web-applications

以下是来自servlet的片段,它试图从URL获取图像。我已经获取了字节。现在如何在网页上显示图像?

    response.setContentType("text/html;charset=UTF-8");

    PrintWriter out = response.getWriter();

    try {
        URL url = new URL("https://abc/zhdhaG1z_bigger.jpeg");
        InputStream stream = new BufferedInputStream(url.openStream());
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte buf[] = new byte[1024];
        int n = 0;
        while(-1 != (n = stream.read(buf)) ) {
            bos.write(buf, 0, n);
        }
        byte res[] = bos.toByteArray();

    } finally {            
        out.close();
    }

1 个答案:

答案 0 :(得分:0)

你可以像这样重写你的代码......看看这是否有帮助

public void doGet(HttpRequest request,HttpResponse response)throws ServletException{

response.setContentType("image/jpeg;charset=UTF-8");    
response.addHeader("content-disposition", "inline;filename=Default.jpeg");

    try {
        URL url = new URL("https://abc/zhdhaG1z_bigger.jpeg");
        InputStream stream = new BufferedInputStream(url.openStream());
        ByteArrayOutputStream bos = new OutputStream();
        byte buf[] = new byte[1024];
        int n = 0;
        while(-1 != (n = stream.read(buf)) ) {
            bos.write(buf, 0, n);
        }

    } 
     catch(Exception e){
            e.printStackTarce();
     }

    finally {            
        out.close();
    }
}