开发者

How to convert byte array to image [duplicate]

This question already has answers here: Show image as byte[] from database as graphic image in JSF page (2 answers) Closed 6 years ag开发者_运维问答o.

I have a SQL database that contains images stored as a byte array. I have done some searching and have not found much on how to convert these into a useable Image type for a JSF page. Any help would be greatly appreciated!

Thanks in advance!

(using JSF 2.0)


Just a create a controller that output the right media type (image/*) and output the bytes. There is no need to convert anything. If you want to manipulate the images then yes you can convert it using ImageIO.read. But from your question it sounds like you just want to display the image.

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    byte[] bytes = ...  
    resp.setContentType(mimeType);    
    OutputStream out = resp.getOutputStream();
    out.write(bytes);
}


Try doing something similar to this.


This is not a working example but it outlines the approach on how to dynamically display an image stored in database. You have to create a servlet (depending on the framework you use it may be a struts action or so) that behaves like an image:

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

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        /* this is pseudo code, retrieve the image and its metadata from database.
         * Maybe you do not want to use a parameter but a RESTful approach, e.g. '/images/image1234'.
         */
        MyImage myimg = MyDatabase.getImage(request.getParameter("imageID"));

        /* you may want to support different encodings (e.g. JPG, PNG, TIFF) */
        response.setContentType(myimg.getContentType());

        /* obtain output stream and stream the bytes back to the client */
        OutputStream out = response.getOutputStream();

        /* stream it, here you have different options, finally close the stream */
        out.write(myimg.getBytes());
    }

}

In your JSF page you have to reference the servlet accordingly:

<img src=".../images/image1234" />

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜