java 小服务程序 : get image from url and display it

标签 java servlets

我将如何从 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);     
    }  

然而,返回的只是一个损坏的图像文件。

最佳答案

你应该使用 OutputStream from the response而不是作家。作家处理字符数据。另外你不妨set the MIME type correctly用于响应。

关于java 小服务程序 : get image from url and display it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26643916/

相关文章:

java - Json预处理性能问题

java - 如何从 JTextArea 中删除 Ascii 代码?

java - Velocity 模板引擎如何用于 Java Web 应用程序中的 View ?

java - Servlet 返回 JSTL 结果或对象列表?

java - 使用 HttpServletRequest 获取请求发送者的 URL

带有目录/包的defineClass的Java ClassLoader格式?

java - JSF 生命周期和自定义组件

java - 从 SessionFactoryImpl 解包 Jdbc4Connection

java - NetBeans Servlet MySQL

javascript - 如何将表单提交的时间发送给servlet?