How to display image from mysql database using spring mvc

I wrote below code in my controller and it's working fine for me.

In my project, User contain Profile Object which has photo @Lob. Modify this code as per your attributes.

    byte[] encodeBase64 = Base64.encode(user.getProfile().getPhoto());
    String base64Encoded = new String(encodeBase64, "UTF-8");
    mav.addObject("userImage", base64Encoded );

In JSP file, I wrote code

<img src="data:image/jpeg;base64,${userImage}" />

For this, you require common-codec jar.

Also, you can use a custom tag for showing image.


I'm finally able to display the image on my jsp. what i did.

I separately created a controller like this.

@Controller
@RequestMapping("/myImage")
public class ImageController {

@Resource(name="categoryService")
private CategoryService categoryService;

@Resource(name="itemService")
private ItemService itemService;

@RequestMapping(value = "/imageDisplay", method = RequestMethod.GET)
  public void showImage(@RequestParam("id") Integer itemId, HttpServletResponse response,HttpServletRequest request) 
          throws ServletException, IOException{


    Item item = itemService.get(itemId);        
    response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
    response.getOutputStream().write(item.getItemImage());


    response.getOutputStream().close();

and in the jsp i did this

<img src="/Project1/myImage/imageDisplay?id=${item.itemId}"/>

And the image was successfully displayed.


One more thing you can do for displaying the image in jsp from database. suppose you need to display images of all user in jsp. for this you can create your own custome jstl tag which contain code for converting byte image to base64 image.

here in my project the image is in Profile class

i.e user.getProfile().getPhoto()

    package com.spring.tags;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.codec.base64.Base64;

public class UserImage extends SimpleTagSupport {

    private byte[] usrImage;

    public void setUsrImage(byte[] usrImage) {
        this.usrImage = usrImage;
    }

@Override
    public void doTag() throws JspException, IOException {
        System.out.println("tag lib");
        try {
            JspWriter out = getJspContext().getOut();
            if (usrImage != null && usrImage.length > 0) {
                byte[] encodeBase64 = Base64.encode(usrImage);
                String base64Encoded = new String(encodeBase64, "UTF-8");
                out.print("data:image/jpeg;base64,"+base64Encoded);

            }
        } catch (Exception e) {
            throw new JspException("Error: " + e.getMessage());     }
    }   
}

create tld file in WebContent. i have create file in my taglib folder

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd">
  <tlib-version>1.0</tlib-version>
    <short-name>ui</short-name>
    <uri>/taglib/userimage</uri>
    <tag>
        <name>image</name>
        <tag-class>com.spring.tags.UserImage</tag-class>
        <body-content>empty</body-content>
        <info>This Tag Displayes current user profile image</info>
        <attribute>
            <name>usrImage</name>
            <required>true</required>
            <description>Provide a display format</description>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
    </tag>
</taglib>

Now you can write code in jsp for displaying image.

<img src="<ui:image usrImage='${user.profile.photo}' />

Every time no need to convert image in controller just pass byte image to jsp and our custome tag will convert byte image and dispay it in view page.

Note: include custome tag file in jsp file

<%@ taglib uri="/taglib/userimage.tld" prefix="ui"%>