gpt4 book ai didi

grails - 如何在http请求中渲染png?

转载 作者:行者123 更新时间:2023-12-02 15:50:47 24 4
gpt4 key购买 nike

我有一个 Controller 从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"
}

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

最佳答案

我已经通过将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>

关于grails - 如何在http请求中渲染png?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39758797/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com