java、python 图片Base64编码和解码
注:最近做的一个项目需要从android上传图片到服务端,并返回结果。因为android用的是java编码,而服务端用的是python,常规的编码解码传输总是有问题,所以想到了用base64来统一两边的编码解码。
Java进行Base64编码
//将本地图片进行Base64位编码
// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
public static String encodeImgageToBase64(File imageFile) {
ByteArrayOutputStream outputStream = null;
try {
BufferedImage bufferedImage = ImageIO.read(imageFile);
outputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "jpg", outputStream);
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
// 返回Base64编码过的字节数组字符串
return encoder.encode(outputStream.toByteArray());
}
Java进行Base64解码
//Base64位编码的图片进行解码,并保存到指定目录
public static void decodeBase64ToImage(String base64, String path, String imgName) {
BASE64Decoder decoder = new BASE64Decoder();
try {
FileOutputStream write = new FileOutputStream(new File(path + imgName));
byte[] decoderBytes = decoder.decodeBuffer(base64);
write.write(decoderBytes);
write.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Python进行Base64解码
import base64
from PIL import Image
from io import BytesIO
base64_data = '...' #图片进行base64编码形成的字符串
base64_data = base64_data.replace('↵','').replace('%0A', '')
img = base64.b64decode(base64_data)
image_data = BytesIO(img)
#保存图片
img.save(image_data)
#显示图片
im = Image.open(image_data)
im.show()
注:图片进行base64编码之后形成的是string字符串,所以数据传输传输的是字符串流,base64解码的时候也要先将数据转换为str类型。