提交 | 用户 | age
|
248c35
|
1 |
package com.hx.util; |
F |
2 |
|
|
3 |
import sun.misc.BASE64Decoder; |
|
4 |
import sun.misc.BASE64Encoder; |
|
5 |
|
|
6 |
import java.io.*; |
|
7 |
|
|
8 |
/** |
|
9 |
* 图片和base64字符转换工具 |
|
10 |
* @USER: fhx |
|
11 |
* @DATE: 2023/4/6 |
|
12 |
**/ |
|
13 |
public class ImageBase64Util { |
|
14 |
|
|
15 |
/** |
|
16 |
* base64字符串转化成图片 |
|
17 |
* @param base64 |
|
18 |
* @param fileName |
|
19 |
* @param filePath |
|
20 |
* @return |
|
21 |
* @throws Exception |
|
22 |
*/ |
|
23 |
public static File base64ToFile(String base64, String fileName, String filePath) throws Exception { |
|
24 |
if(base64.contains("data:image")){ |
|
25 |
base64 = base64.substring(base64.indexOf(",")+1); |
|
26 |
} |
|
27 |
base64 = base64.replace("\r\n", ""); |
|
28 |
//创建文件目录 |
|
29 |
File file = File.createTempFile(base64, fileName, new File(filePath)); |
|
30 |
BufferedOutputStream bos = null; |
|
31 |
FileOutputStream fos = null; |
|
32 |
try { |
|
33 |
BASE64Decoder decoder = new BASE64Decoder(); |
|
34 |
byte[] bytes = decoder.decodeBuffer(base64); |
|
35 |
fos = new FileOutputStream(file); |
|
36 |
bos = new BufferedOutputStream(fos); |
|
37 |
bos.write(bytes); |
|
38 |
}finally { |
|
39 |
if (bos != null) { |
|
40 |
try { |
|
41 |
bos.close(); |
|
42 |
} catch (IOException e) { |
|
43 |
e.printStackTrace(); |
|
44 |
} |
|
45 |
} |
|
46 |
if (fos != null) { |
|
47 |
try { |
|
48 |
fos.close(); |
|
49 |
} catch (IOException e) { |
|
50 |
e.printStackTrace(); |
|
51 |
} |
|
52 |
} |
|
53 |
} |
|
54 |
return file; |
|
55 |
} |
|
56 |
|
|
57 |
/** |
|
58 |
* 图片转化成base64字符串 |
|
59 |
* @param imgFile |
|
60 |
* @return |
|
61 |
*/ |
|
62 |
public static String GetImageStr(File imgFile) {//将图片文件转化为字节数组字符串,并对其进行Base64编码处理 |
|
63 |
InputStream in = null; |
|
64 |
byte[] data = null; |
|
65 |
//读取图片字节数组 |
|
66 |
try { |
|
67 |
in = new FileInputStream(imgFile); |
|
68 |
data = new byte[in.available()]; |
|
69 |
in.read(data); |
|
70 |
in.close(); |
|
71 |
} catch (IOException e) { |
|
72 |
e.printStackTrace(); |
|
73 |
} |
|
74 |
//对字节数组Base64编码 |
|
75 |
BASE64Encoder encoder = new BASE64Encoder(); |
|
76 |
return encoder.encode(data);//返回Base64编码过的字节数组字符串 |
|
77 |
} |
|
78 |
|
|
79 |
} |