JAVA--将图片转为BASE64编码并返回thymeleaf页面

controller

 1 package cn.lntop.controller.test;
 2 
 3 import java.util.ArrayList;
 4 import java.util.HashMap;
 5 import java.util.List;
 6 import java.util.Map;
 7 
 8 import javax.servlet.http.HttpServletRequest;
 9 
10 import org.apache.commons.lang3.StringUtils;
11 import org.springframework.beans.factory.annotation.Autowired;
12 import org.springframework.beans.factory.annotation.Value;
13 import org.springframework.stereotype.Controller;
14 import org.springframework.ui.ModelMap;
15 import org.springframework.web.bind.annotation.RequestMapping;
16 import org.springframework.web.bind.annotation.RequestMethod;
17 import org.springframework.web.bind.annotation.ResponseBody;
18 
19 import cn.lntop.util.ReturnUtil;
20 import tk.mybatis.mapper.util.StringUtil;
21 
22 @Controller
23 @RequestMapping("/test")
24 public class TestController {
25     
26     /**
27      * 取得电脑信息
28      * @param request
29      * @return
30      */
31     @RequestMapping(value="/test/comInfo", method = {RequestMethod.GET})
32     public ModelMap getTestInfo(HttpServletRequest request) {
33          // 取得URL后的参数
34         String comId = request.getParameter("comId");
35         Map<String, Object> param = new HashMap<String, Object>();
36         param.put("comId", comId)
37         // 查询电脑基本信息步骤--略
38      ComInfo com = comService.selectComInfo(param); 
39         try {
40             // 取得图片所在位置
41             String imgPath = this.getClass().getResource("/").getPath() + "/" + com.getImageName();
42             // 将图片转化为base64
43             String base64 = ImgBase64Util.getImgStr(imgPath);
44             // 拼接图片头
45             String head = headFile(imgPath);
46             com.setHeadData(head + base64);
47         } catch (Exception e) {
48             e.printStackTrace();
49         }
50         ModelMap map = new ModelMap();
51         map.put("com", com);
52         return ReturnUtil.Success("操作成功", map, null);
53     }
54 
55     /**
56      * 拼接Base64头信息
57      * @param urlString
58      */
59     public String headFile(String urlString) {
60         String head = "";
61         String type = urlString.substring(urlString.lastIndexOf('.') + 1);
62         if ("png".equals(type)) {
63             head = "data:image/png;base64,";
64         } else if ("jpg".equals(type)) {
65             head = "data:image/jpg;base64,";
66         } else if ("jpeg".equals(type)) {
67             head = "data:image/jpeg;base64,";
68         } else {
69             head = "data:image/jpg;base64,";
70         }
71         return head;
72     }
73     
74 }

Base64工具类

 1 package cn.test.util;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 import java.io.InputStream;
 7 import java.io.OutputStream;
 8 
 9 import org.apache.commons.codec.binary.Base64;
10 
11 
12 /**
13  * 将图片转换为Base64
14  * 将base64编码字符串解码成img图片
15  *
16  */
17 public class ImgBase64Util {
18 
19     /**
20      * 将图片转换成Base64编码
21      * @param imgFile 待处理图片
22      * @return
23      */
24     public static String getImgStr(String imgFile){
25         
26         InputStream in = null;
27         byte[] data = null;
28         //读取图片字节数组
29         try 
30         {
31             in = new FileInputStream(imgFile);        
32             data = new byte[in.available()];
33             in.read(data);
34             in.close();
35         } 
36         catch (IOException e) 
37         {
38             e.printStackTrace();
39         }
40         return new String(Base64.encodeBase64(data));
41     }
42     
43     /**
44      * 对字节数组字符串进行Base64解码并生成图片
45      * @param imgStr 图片数据
46      * @param imgFilePath 保存图片全路径地址
47      * @return
48      */
49     public static boolean generateImage(String imgStr,String imgFilePath){
50         //
51         if (imgStr == null) //图像数据为空
52             return false;
53      
54         try 
55         {
56             //Base64解码
57             byte[] b = Base64.decodeBase64(imgStr);
58             for(int i=0;i<b.length;++i)
59             {
60                 if(b[i]<0)
61                 {//调整异常数据
62                     b[i]+=256;
63                 }
64             }
65             //生成jpeg图片
66 
67             OutputStream out = new FileOutputStream(imgFilePath);    
68             out.write(b);
69             out.flush();
70             out.close();
71             return true;
72         } 
73         catch (Exception e) 
74         {
75             return false;
76         }
77     }
78     
79     public static void main(String[] args) {
80 //        String imgFile = "d:\3.jpg";//待处理的图片
81 //        String imgbese=getImgStr(imgFile);
82 //        System.out.println(imgbese.length());
83 //        System.out.println(imgbese);
84 //        String imgFilePath = "d:\332.jpg";//新生成的图片
85 //        generateImage(imgbese,imgFilePath);
86     }
87 }

返回thymeleaf格式

 1 package cn.test.util;
 2 
 3 import org.apache.commons.lang3.StringUtils;
 4 import org.springframework.ui.ModelMap;
 5 
 6 /**
 7  * JSON统一返回数据格式
 8 
 9  */
10 public class ReturnUtil {
11 
12     public static ModelMap Success(String msg, Object obj, String referer) {
13         msg = StringUtils.isEmpty(msg) || StringUtils.isBlank(msg) ? "操作成功" : msg;
14         ModelMap mp = new ModelMap();
15         mp.put("status", 1);
16         mp.put("state", "success");
17         mp.put("msg", msg);
18         mp.put("referer", referer);
19         mp.put("result", obj);
20         return mp;
21     }
22 
23     public static ModelMap Success(String msg, Object obj) {
24         msg = StringUtils.isEmpty(msg) || StringUtils.isBlank(msg) ? "操作成功" : msg;
25         ModelMap mp = new ModelMap();
26         mp.put("status", 1);
27         mp.put("state", "success");
28         mp.put("msg", msg);
29         mp.put("referer", null);
30         mp.put("result", obj);
31         return mp;
32     }
33     public static ModelMap Success(String msg) {
34         msg = StringUtils.isEmpty(msg) || StringUtils.isBlank(msg) ? "操作成功" : msg;
35         ModelMap mp = new ModelMap();
36         mp.put("status", 1);
37         mp.put("state", "success");
38         mp.put("msg", msg);
39         mp.put("referer", null);
40         mp.put("result", null);
41         return mp;
42     }
43 
44     public static ModelMap Error(String msg, Object obj, String referer) {
45         msg = StringUtils.isEmpty(msg) || StringUtils.isBlank(msg) ? "操作失败" : msg;
46         ModelMap mp = new ModelMap();
47         mp.put("status", 0);
48         mp.put("state", "error");
49         mp.put("msg", msg);
50         mp.put("referer", referer);
51         mp.put("result", obj);
52         return mp;
53     }
54 
55     public static ModelMap Error(String msg, Object obj) {
56         msg = StringUtils.isEmpty(msg) || StringUtils.isBlank(msg) ? "操作失败" : msg;
57         ModelMap mp = new ModelMap();
58         mp.put("status", 0);
59         mp.put("state", "error");
60         mp.put("msg", msg);
61         mp.put("referer", null);
62         mp.put("result", obj);
63         return mp;
64     }
65 
66     public static ModelMap Error(String msg) {
67         msg = StringUtils.isEmpty(msg) || StringUtils.isBlank(msg) ? "操作失败" : msg;
68         ModelMap mp = new ModelMap();
69         mp.put("status", 0);
70         mp.put("state", "error");
71         mp.put("msg", msg);
72         mp.put("referer", null);
73         mp.put("result", null);
74         return mp;
75     }
76 }
View Code

thymeleaf页面

 1 <!DOCTYPE html>
 2 <html lang="en" xmlns:th="http://www.thymeleaf.org">
 3     <head>
 4         <meta charset="utf-8" />
 5         <title></title>
 6         <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
 7         <meta name="format-detection" content="telephone=no,email=no,adress=no" />
 8         <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
 9         <meta name="keywords" content="">
10         <meta name="description" content="">
11         <meta name="author" content="">
12     </head>
13     <body class="gray-bg">
14         <span>桌面图片</span>
15         <img th:src="${result.com.headData}" class="header-img"/>
16     </body>
17 </html>
原文地址:https://www.cnblogs.com/aiyowei/p/10092948.html