在JSF页面中将图像作为byte []显示为图形图像 [英] Show image as byte[] from database as graphic image in JSF page

查看:110
本文介绍了在JSF页面中将图像作为byte []显示为图形图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的图像内容为 byte [] 来自数据库。

I have image content as byte[] from database.

private byte[] image;

如何在JSF页面中将该字节数组显示为真实的图形图像?

How can I show that byte array as a real graphic image in JSF page?

推荐答案

< h:graphicImage> 无法直接实现。它只能指向一个URL,而不能指向 byte [] ,也不能指向 InputStream 。基本上,您需要确保这些字节可以直接作为给定URL上的HTTP响应使用,然后您可以在< h:graphicImage> 中使用(或者甚至纯HTML < img> )。

This is not directly possible with <h:graphicImage>. It can only point to an URL, not to a byte[] nor InputStream. Basically, you need to make sure that those bytes are directly available as a HTTP response on the given URL, which you can then use in <h:graphicImage> (or even plain HTML <img>).

如果您通过ID识别图像,如下所示:

Provided that you're identifying the image by its ID like so:

<h:graphicImage value="/image/#{someBean.imageId}" />

以下是这种servlet的启动示例:

Here's a kickoff example of such a servlet:

@WebServlet("/image/*")
public class ImageServlet extends HttpServlet {

    @EJB
    private ImageService service;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Long id = Long.valueOf(request.getPathInfo().substring(1));
        Image image = service.find(id);
        response.setContentType(getServletContext().getMimeType(image.getName()));
        response.setContentLength(image.getBytes().length);
        response.getOutputStream().write(image.getBytes());
    }

}

更高级的抽象模板静态资源servlet,支持HTTP缓存,可以在这个答案中找到,以及从数据库提供服务的具体示例。

A more advanced abstract template for a static resource servlet, supporting HTTP caching, can be found in this answer, along with a concrete example for serving from database.

如果您碰巧在JSF 2.2 +上使用JSF实用程序库 OmniFaces CDI环境,然后您可以使用其 < o:graphicImage> 可以更直观地使用。

If you happen to use JSF utility library OmniFaces on a JSF 2.2 + CDI environment, then you can instead use its <o:graphicImage> which can be used much more intuitively.

<o:graphicImage value="#{imageBean.getBytes(someBean.imageId)}" />

@Named
@ApplicationScoped
public class ImageBean {

    @EJB
    private ImageService service;

    public byte[] getBytes(Long imageId) {
        return service.getImageBytes(imageId);
    }

}

这篇关于在JSF页面中将图像作为byte []显示为图形图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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