如何高效处理网络传输中的图片Base64格式转换问题
通常网络传输图片会采用 base64 格式。在编程过程中,会遇到需要将图片文件读取为 base64 格式的情况,也会遇到将 base64 格式的字符串转化为图片的情况。

下面是我写的工具类
注:base64转图片时需要先去掉前缀
package com.sharetime.util;
import com.ctc.wstx.util.StringUtil;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;
/**
* @Author: yd
* @Date: 2018/7/29 11:05
* @Version 1.0
*/
public class Base64Utils {
/**
* 将图片文件转换成base64字符串,参数为该图片的路径
*
* @param imageFile
* @return java.lang.String
*/
public String ImageToBase64(String imageFile) {
InputStream in = null;
byte[] data = null;
// 读取图片字节数组
try {
in = new FileInputStream(imageFile);
data = new byte[in.available()];
[id_1363025664]
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
if (data != null) {
return "data:image/jpeg;base64," + encoder.encode(data);// 返回Base64编码过的字节数组字符串
}
return null;
}
/**
* 将base64解码成图片并保存在传入的路径下
* 第一个参数为base64 ,第二个参数为路径
*
* @param base64, imgFilePath
* @return boolean
*/
public boolean Base64ToImage使用字符串 base64 和字符串 imgFilePath 作为参数。
// 对字节数组字符串进行Base64解码并生成图片
if (base64 == null) // 图像数据为空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byteb 等于 decoder 对 base64 进行解码后的缓冲区。
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
OutputStream out = new创建一个用于写入文件的输出流对象,该对象指向指定的图像文件路径 imgFilePath 。
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
/**
* 用来测试工具类是否成功
*
* @param args
* @return void
*/
public static void main(String[] args) {
String path = "C:/Users/YD/Pictures/1.jpg";
Base64Utils base64Utils = new Base64Utils();
使用 base64Utils 类的 ImageToBase64 方法,将路径 path 转换为 base64 编码的字符串 s 。
System.out.println(s);
String newpath = C 盘下的 Users 文件夹中的 YD 文件夹里的 Pictures 文件夹中的 asd.jpg;
booleanb 等于 base64Utils 中的 Base64ToImage 方法,该方法将字符串 s 转换为图像并保存到新路径 newpath 中。
System.out.println(b);
}
}
需要注意的是,在网站上,src=base64 的格式能够将图片显示出来,并且在图片前面需要加入标识 data:image/jpeg;base64 。
因此,当在服务端获取到网页传过来的 base64 字符串时,要留意其是否包含前缀。如果包含前缀,就需要将其去掉,然后再进行转换。
image为从网络传过来的base64格式的字符串
int i = image.indexOf("base64,")+7;获取以“data:image/gif;base64,”开头的坐标
String newImage = image.substring(i, image.length());//去除前缀