python 图像 音频 转base64

处理图像和音频的时候,通常拿到的数据以及返回的结果需要转成base64。最近为了测试算法接口,找了下面这一小段代码,实现图像、音频与对应base64编码的相互转换,做个记录(其实也有许多在线工具可以将图像转base64)。关于base64的内容可以查看廖雪峰的网站base64 - 廖雪峰的官方网站

import matplotlib.pyplot as plt  
import base64
import cv2
def ToBase64(file, txt):
    with open(file, 'rb') as fileObj:
        audio_data = fileObj.read()
        base64_data = base64.b64encode(audio_data)
        fout = open(txt, 'w')
        fout.write(base64_data.decode())
        fout.close()


def ToFile(txt, file):
    with open(txt, 'r') as fileObj:
        base64_data = fileObj.read()
        ori_image_data = base64.b64decode(base64_data)
        fout = open(file, 'wb')
        fout.write(ori_image_data)
        fout.close()

ToBase64("./street_music.wav",'desk_base64.txt')  # 文件转换为base64
ToFile("./desk_base64.txt",'desk_cp_by_base64.jpg')  # base64编码转换为二进制文件
img = cv2.imread('desk_cp_by_base64.jpg')
plt.imshow(img)
plt.show

  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值