在浏览器中显示来自控制器的图像对象 [英] Displaying image object from controller in the browser

查看:69
本文介绍了在浏览器中显示来自控制器的图像对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java上使用playframework 2.2.1,
我正在尝试通过BufferedImage或ByteArray或ByteArrayInputStream
查看模板以便直接在内存中将其显示在浏览器中,
而不保存到服务器存储中.
在我的视图模板中,我请求一张图片:

I use playframework 2.2.1 with Java,
I am trying to pass BufferedImage or ByteArray or ByteArrayInputStream
to view template in order to display it in browser directly from memory,
without saving to server storage.
in my view template I request an image:

<img src="@{Application.getImage()}"/>

我的应用程序控制器:

public static Result getImage() throws IOException{  
    BufferedImage image = ImageIO.read(new File("public/img/1.jpg"));  
    //some image manipulations  
    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    ImageIO.write(image, "jpg", baos);  
    return ok(baos.toByteArray()).as("image/jpg");  
}

在生成的html中,我得到:

in generated html I get:

<img src="SimpleResult(200, Map(Content-Type -&gt; image/jpg))">

我找到了有关此主题的一些信息(一个两个

I've found some info about this topic (one, two, three, four),
but it is usually related to older versions, or Scala versions of play.
Please suggest anything or point to my mistake,
Thanks

推荐答案

您应该使用getImage()操作的路由,而不是src属性中的Result:

You should use a route to getImage() action instead of its Result in src attribute:

<img src='@routes.Application.getImage()'/>

顺便说一句:尽管我们不知道您对图像进行了哪种操作,但有时还是有必要将它们保存到光盘中-特别是在有可能重新使用它们的情况下.在这种情况下,您可以使用以下命令将其退回:

BTW: Although we don't know what kind of manipulation you do with images, sometimes it makes sense to save them to disc - especially if there is possibility that they will be reused. In such case you can return it with:

return ok(new File("/path/to/file"));

当然仍然使用route作为src;)

这篇关于在浏览器中显示来自控制器的图像对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆