How to convert byte array to image [duplicate]
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.
精彩评论