将数据库中的图像显示为字节 [] 作为 JSF 页面中的图形图像 [英] Show image as byte[] from database as graphic image in JSF page

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

问题描述

我有来自数据库的 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?

推荐答案

这在 中无法直接实现.它只能指向一个 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 + CDI 环境中使用 JSF 实用程序库 OmniFaces,那么您可以改用它的 <一个 href="http://showcase.omnifaces.org/components/graphicImage" rel="noreferrer"> 可以更直观地使用.

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 页面中的图形图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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