How to convert byte array to image [duplicate]

橙三吉。 提交于 2019-12-13 08:55:20

问题


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)


回答1:


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);
}



回答2:


Try doing something similar to this.




回答3:


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.



来源:https://stackoverflow.com/questions/7040848/how-to-convert-byte-array-to-image

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!