如何在http请求中呈现png?

时间:2016-09-28 22:48:15

标签: grails

我有一个控制器从GET请求连接到此方法:

def renderPNG() {
    URL url = new URL("https://absolute.url.png");
    BufferedImage img = ImageIO.read(url);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(img, "png", baos);
    InputStream is = new ByteArrayInputStream(baos.toByteArray());
    DataInputStream ds = new DataInputStream(is);

    render file: ds, contentType: "image/png"
}

但是当我在响应中获得图像时,它会被奇怪的字符编码。如何检索图像并正确解码,以便浏览器呈现?

1 个答案:

答案 0 :(得分:0)

我已经通过将inputStream转换为Base64.encode getbyte代码来解决您的问题,将其呈现给Veiw。

def renderPNG () {
 URL url = new URL("http://tineye.com/images/widgets/mona.jpg");
            BufferedImage img = ImageIO.read(url);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(img, "png", baos);
            InputStream is = new  ByteArrayInputStream(baos.toByteArray()); 
      render(Base64.encode(is?.getBytes()))
}

Java脚本代码获取图像

 /* fetch the user image */
            $.ajax({
                url: "/controller/renderPNG",
                type: 'GET',
                cache: false,
                success: function (result) {
                    document.getElementById('userImage').src = "data:image/png;base64," + result;
                }
            });

我们想要渲染图像的HTML代码

<div><img id="userImage" src=""alt="User Image"></div>