首页 > 技术文章 > 接口上传base64编码图片

-lpf 2016-08-31 18:31 原文

 1 package com.*.util;
 2 
 3 import java.io.FileInputStream;
 4 
 5 
 6 import java.io.FileOutputStream;
 7 import java.io.IOException;
 8 import java.io.InputStream;
 9 import java.io.OutputStream;
10 import java.util.Date;
11 
12 import Decoder.BASE64Decoder;
13 import Decoder.BASE64Encoder;
14 
15 public class Base64ImgUtils {
16     public static void main(String[] args) {
17         String strImg = GetImageStr();
18         System.out.println(strImg);        
19         GenerateImage(strImg);
20     }
21 
22     /**
23      * 图片转化成base64字符串
24      * GetImageStr
25      * 2016年8月31日下午3:37:40   
26      * @param
27      * @return
28      */
29     public static String GetImageStr() {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
30         String imgFile = "D:/486e407765c21edd9cbffca69717efb1.jpg";// 待处理的图片
31         InputStream in = null;
32         byte[] data = null;
33         // 读取图片字节数组
34         try {
35             in = new FileInputStream(imgFile);
36             data = new byte[in.available()];
37             in.read(data);
38             in.close();
39         } catch (IOException e) {
40             e.printStackTrace();
41         }
42         // 对字节数组Base64编码
43         BASE64Encoder encoder = new BASE64Encoder();
44         String imghead="data:image/jpg;base64,";//
45         return imghead+encoder.encode(data);// 返回Base64编码过的字节数组字符串
46     }
47 
48     /**
49      * base64字符串转化成图片
50      * GenerateImage
51      * 2016年8月31日下午3:33:12   
52      * @param
53      * @return
54      */
55     public static String GenerateImage(String imgStr) { // 对字节数组字符串进行Base64解码并生成图片
56         if (imgStr == null){ // 图像数据为空
57             return "";
58         }
59         String classPath = new Base64ImgUtils().getClass().getResource("").getPath();
60         String path = classPath.substring(0, classPath.indexOf("WEB-INF"));
61         System.out.println(path);
62         BASE64Decoder decoder = new BASE64Decoder();
63         try {
64             String imghead=imgStr.substring(0,imgStr.indexOf(";")).replace("data:image/", ".");//获取图片扩展名
65             imgStr=imgStr.substring(imgStr.indexOf(",")+1);//图片内容
66                                    
67             // Base64解码
68             byte[] b = decoder.decodeBuffer(imgStr);
69             for (int i = 0; i < b.length; ++i) {
70                 if (b[i] < 0) {// 调整异常数据
71                     b[i] += 256;
72                 }
73             }
74             // 生成jpeg图片
75             String filename="upload/"+new Date().getTime()+imghead;//名称
76             String imgFilePath =path+"/"+filename;// 新生成的图片
77             OutputStream out = new FileOutputStream(imgFilePath);
78             out.write(b);
79             out.flush();
80             out.close();
81             return filename;
82         } catch (Exception e) {
83             return "";
84         }
85     }
86 
87     
88 }

 

推荐阅读