图片转bas464编码字符串

在用markdown编写文档的时候,发现图片上传比较麻烦。特别是在网络中上传的时候,文本迁移还容易,但是图片就很难保存下来了,所以就在网上看到一个解决办法,就是把图片转换为base64编码

  • 优点:本地存储
  • 缺点:转换要执行代码,其次,转成的图片太长,影响源markdown文档阅读
    下面是代码:
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
public class ImageToStr {
public static boolean generateImage(String imgStr, String path) {
if (imgStr == null)
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
// 解密
byte[] b = decoder.decodeBuffer(imgStr);
// 处理数据
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
OutputStream out = new FileOutputStream(path);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
/**
* @return
* @Description: 根据图片转换为base64编码字符串
* @Author:
* @CreateTime:
*/
public static String getImageStr(String imgFile) {
InputStream inputStream = null;
byte[] data = null;
try {
inputStream = new FileInputStream(imgFile);
data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 加密
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
public static void main(String[] args) {
String strImg = getImageStr("C:\\Users\\tang\\Desktop\\7.png");
// 在浏览器中使用时,需要加上下面的前缀方可
System.out.println("data:image/png;base64," + strImg);
}
}