-
Notifications
You must be signed in to change notification settings - Fork 1
/
ImageBase64Utils.java
90 lines (83 loc) · 2.67 KB
/
ImageBase64Utils.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package MyExamples.MergeFace;
import java.io.*;
/**
* Created by herbertyang on 2019-04-21.
*/
public class ImageBase64Utils {
public static String bytesToBase64(byte[] bytes) {
return org.apache.commons.codec.binary.Base64.encodeBase64String(bytes);// 返回Base64编码过的字节数组字符串
}
/**
* 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
*
* @param path 图片路径
* @return base64字符串
*/
public static String imageToBase64(String path) throws IOException {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
byte[] data = null;
// 读取图片字节数组
InputStream in = null;
try {
in = new FileInputStream(path);
data = new byte[in.available()];
in.read(data);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return org.apache.commons.codec.binary.Base64.encodeBase64String(data);// 返回Base64编码过的字节数组字符串
}
/**
* 处理Base64解码并写图片到指定位置
*
* @param base64 图片Base64数据
* @param path 图片保存路径
* @return
*/
public static boolean base64ToImageFile(String base64, String path) throws IOException {// 对字节数组字符串进行Base64解码并生成图片
// 生成jpeg图片
try {
OutputStream out = new FileOutputStream(path);
return base64ToImageOutput(base64, out);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return false;
}
/**
* 处理Base64解码并输出流
*
* @param base64
* @param out
* @return
*/
public static boolean base64ToImageOutput(String base64, OutputStream out) throws IOException {
if (base64 == null) { // 图像数据为空
return false;
}
try {
// Base64解码
byte[] bytes = org.apache.commons.codec.binary.Base64.decodeBase64(base64);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}
// 生成jpeg图片
out.write(bytes);
out.flush();
return true;
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}