python 图像 音频 转base64

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

 

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章