无法在百里香中显示byte []图像

问题描述 投票:0回答:3

我无法在thymleaf中显示字节图像,它来自数据库,因为blob然后转换为byte [],当我从查询成功实现的数据库中获取图像时,但是它无法在thymleaf中显示,下面是代码

DaoImpl在daoimpl中对此函数进行编码,以便从数据库中检索图像

在此函数中使用查询blob从数据库中选择然后blob以字节和字节的形式直接发送到控制器

@Override
public byte[] stockProductMenData() 
{
    Session session = getSession();

    byte[] Imagebytes = null;
    Query query = session.createQuery("select sp.stockProductPic "
            + "from StockType st,StockProduct sp"
            + " where st.stockTypeId=sp.stockTypeId and st.stockTypeName = :stockTypeName");
    query.setParameter("stockTypeName","MEN");



     List<Blob> list = query.list();
     System.out.println("List size :"+list.size()); 

     Iterator<Blob> itr = list.iterator();

      while(itr.hasNext())
      {  
         Blob blob = itr.next();
         try {
            Imagebytes =blob.getBytes(1,(int) blob.length());
            System.out.println("dddddd"+Imagebytes);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            System.out.println("eeeeeee"+e);
        }
      }

控制器在控制器中我们接收字节数组并在base64中编码并发送到百万美元页面

@RequestMapping(value = "/mens" , method = RequestMethod.GET)
public ModelAndView custMen()
{
    ModelAndView modelAndView =new ModelAndView();

    byte[] picContent = customerDao.stockProductMenData();
    byte[] encoded = Base64.getEncoder().encode(picContent);
    System.out.println("ssssssssss"+picContent);



                modelAndView.addObject("pic",encoded);
                modelAndView.setViewName("mens");
                return modelAndView;

}

这里有百里香的前端我们收到了pic的对象并且使用百里香叶显示但是没有显示pic

    <a href="mens_single.html">
    <div class="cbp-pgitem a3ls">
      <div class="cbp-pgitem-flip">
                            <img alt="Image"  th:field="${pic}" width="250" height="250"/>


   </div>
     </div>

java mysql spring hibernate thymeleaf
3个回答
2
投票

您可以使用以下代码

Blob imageBlob = resultSet.getBlob(yourBlobColumnIndex);
byte[] imageBytes = imageBlob.getBytes(i, (int) imageBlob.length());

1
投票

将blob转换为字节,然后使用Base64.getEncoder().encodeToString(byte[] image);将该字节转换为Base64String,需要在Context中将其设置为变量并使用context.setVariable(key, Base64String variable);添加密钥,然后将其传递给Template Engine进行处理,并在Thymeleaf html页面中添加此行<img th:src="@{'data:image/png;base64,' + ${Base64String's key} }" />

此方法适用于添加图像,Qr代码和条形码等,条件是它们可以转换为byte []以进行进一步处理。


0
投票

假设您发送了一个byte []存储在您的数据库中....

  1. 将Base64编码的字符串添加到模型映射中: //I'm using a model here but the concept is the same model.addAttribute("pic",Base64.getEncoder.encodeToString(*your_blob*));
  2. 在你的百里香片中: <img th:src="${pic} == null ? _ : @{'data:image/png;base64,'+${pic}}">

Thymeleaf的模板引擎将有助于将Base64字符串转换为图像。

© www.soinside.com 2019 - 2024. All rights reserved.