Spring - display image on jsp file
Solution 1
You cannot do it like this. Your image must be exposed somehow via normal URL. In Spring MVC create a controller that returns an image (raw data) under particular URL:
@RequestMapping(value = "/imageController/{imageId}")
@ResponseBody
public byte[] helloWorld(@PathVariable long imageId) {
Image image = //obtain Image instance by id somehow from DAO/Hibernate
return image.getData();
}
Now useit in your JSP page. This is how HTTP/HTML work:
<img src="/yourApp/imageController/42.png" alt="car_image"/>
In Spring MVC before 3.1 you might need to do a little bit more coding on controller side. But the principle is the same.
Solution 2
File file = new File("home/user/test.jpg");
FileInputStream fis=new FileInputStream(file);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
int b;
byte[] buffer = new byte[1024];
while((b=fis.read(buffer))!=-1){
bos.write(buffer,0,b);
}
byte[] fileBytes=bos.toByteArray();
fis.close();
bos.close();
byte[] encoded=Base64.encodeBase64(fileBytes);
String encodedString = new String(encoded);
ModelMap map = new ModelMap();
map.put("image", encodedString);
Now use it in your JSP page following as
<img src="data:image/jpeg;base64,${image}" alt="..." width="200" height="200">`
Solution 3
You may need to check this post. I have a similar problem like you and the solution is to convert the byte array to string and set in the img tag like below,
<img src="data:image/jpg;base64,<c:out value='${bean.imageByteArrayString}'/>" />
Solution 4
I was looking fo the right answer for a couple of days , so I will write the good one for me:
My image is already saved in database:
@Entity
@Table(name="PRODUCT")
public class Product {
@Lob
@Column(name="IMG")
private byte[] img;
// setters getters etc
}
Now in my class for example ShowPicture I have to read it:
String encodedImage = Base64.encode(product.getImg());
//setters and getters encodedImage
Then my jsp page:
<img src='data:image/jpg;base64,<s:property value='encodedImage'/>' alt="my image" />
Simple as that ! :)
Solution 5
Maybe it's late, but here I leave something that served me and maybe someone can help.
I'm also using Spring MVC and Hibernate
In the model (entity class) create a variable of type String to do the conversion of type byte to String with Base64.
I did this for a table of countries that I have with its respective flag, and what I wanted was to list in a table in the view all the countries and to the side its flag.
Model (Entity)
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
@Entity
@Table(name = "country")
public class Country implements java.io.Serializable {
private int id;
private String name;
private byte[] flag;
private String base64; //Variable to store the conversion of a data byte type to String
@Transient //Annotation so it does not persist in the database
public String getBase64() {
//Convert the data type byte to String, store it in the variable and return it
return this.base64 = Base64.encode(this.flag);
}
public void setBase64(String base64) {
this.base64 = base64;
}
public Country() {
}
public Country(int id, String name, byte[] flag, String base64) {
this.id = id;
this.name = name;
this.flag = this.flag
this.base64 = this.base64;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "name")
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "flag")
public byte[] getFlag() {
return this.flag;
}
public void setFlag(byte[] flag) {
this.flag = flag;
}
}
Repository - Implements is an interface - AbstractDao is an class Abstract import org.springframework.stereotype.Repository; import application.model.Country; import application.repository.dao.AbstractDao; import application.repository.dao.CountryDao; import org.hibernate.Criteria;
@Repository("countryDao")
public class CountryDaoImpl extends AbstractDao<Integer, Country> implements CountryDao {
@Override
@SuppressWarnings("unchecked")
public List<Country> listCountries() {
Criteria criteria = createEntityCriteria(); //Country.class
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
List<Country> listCountries = criteria.list();
return listCountries;
}
}
Service - implements is an interface
import application.model.Country;
import application.repository.dao.CountryDao;
import application.service.dao.CountryService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("countryService")
public class CountryServiceImpl implements CountryService {
@Autowired
private CountryDao countryDao;
@Override
@Transactional(readOnly = true)
public List<Country> listCountries() {
return countryDao.listCountries();
}
}
Controller
import application.model.Country;
import application.service.dao.CountryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(value = "/countries")
public class CountryController {
@Autowired
private CountryService countryService;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public String ListCountries(Model model) {
model.addAttribute("listcont", countryService.listCountry());
return "countries/countries"; //view
}
}
View - countries/countries.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h3>List Countries</h3>
<table>
<thead>
<tr>
<th>Name</th>
<th>Flag</th>
</tr>
</thead>
<tbody>
<c:forEach items="${listcont}" var="country">
<tr>
<td>${country.name}</td>
<td><img src="data:image/png;base64,${country.base64}" /></
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
bontade
Updated on December 09, 2020Comments
-
bontade over 3 years
my model store image described with file name (as String) and data (as byte array). I use Hibernate and here's my model:
@Entity public class Image { private Long id; private String name; private byte[] data; @Id @GeneratedValue @Column(name = "IMAGE_ID") public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(nullable = false, length = 100) public String getName() { return name; } public void setName(String name) { this.name = name; } @Lob @Column(nullable = false) public byte[] getData() { return data; } public void setData(byte[] data) { this.data = data; } }
But I want to display my stored image, on web site like:
<img src="${image.data}" alt="car_image"/>
How could I do that?
Should I write controller that serve requests for images?
Any code examples?
UPDATE
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView" /> </bean> <bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer"> <property name="definitions"> <list> <value>/WEB-INF/configs/tiles.xml</value> </list> </property> </bean>
-
bontade about 12 yearsI've tryied this solution, but I'm getting 404 error. Is it because of my view configuration, that use Tiles? I've put configurations in update
-
bontade about 12 yearsSo finally, 404 error was caused by servlet mapping, that served requests for regex *.htm. Your solution works! Thanks! Dzięki:D
-
Adrien Be over 11 yearsA "Spring MVC + Hibernate + Maven" fully working example: sites.google.com/site/adrienitnotes/java/…
-
Don Cheadle about 9 yearswhen I try this, I get all sorts of messed up characters, instead of an image
-
Don Cheadle about 9 yearscalling
getData()
onBufferedImage
or similar did not work for me. [This mykong article worked best for me to get byte[] from an image](mkyong.com/java/how-to-convert-bufferedimage-to-byte-in-java). Key is to 1. getBufferedImage
, and 2. getByteArrayOutputStream
then useImageIO.write(buffImage, "jpg", baos)
to load ByteArrayOutputStream then call.toByteArray()
-
Mr. AJ about 9 yearsVery nice solution! Thanks! :)
-
Siddharth over 6 yearsThe method encodeBase64(byte[]) is undefined for the type Base64
-
user404 almost 5 years^ encode64(byte[]) is under this package:
org.apache.commons.codec.binary.Base64