java、python 图片Base64编码和解码

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类型。

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AndrewYy-chan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值