python对图片进行base64编码,互相转换
全程使用openCV,没有PIL
代码:
1 import base64 2 import cv2 3 import sys 4 import numpy as np 5 6 path = sys.argv[1] 7 8 with open(path, "rb") as image_file: 9 encodedImage = base64.b64encode(image_file.read()) 10 imgBase64 = "data:image/jpeg;base64," + encodedImage 11 file = open('imgBase64.txt', 'wb') 12 file.write(imgBase64) 13 file.close() 14 15 npArray = np.fromstring(encodedImage.decode('base64'), np.uint8) 16 image = cv2.imdecode(npArray, cv2.IMREAD_COLOR) 17 cv2.imwrite('img.jpeg',image)
该脚本读取一个图片文件,转换为base64编码后,添加前缀,并保存到txt中。同时解析base64编码,将转换出来的图片保存到当前目录。
读取图片转成base64字符串:
要注意用读文件的方式读取图片,不能用 cv2.imread()。我读取的是 jpeg图片,在网络传输时需要加上前缀 "data:image/jpeg;base64," 。
从base64字符串转为图片:
注意要先去掉前缀 "data:image/jpeg;base64," , 然后再扔到decode函数中。以上是用openCV保存图片,也可以直接用保存文件的方式:
imgData = base64.b64decode(imgString.strip().replace("data:image/jpeg;base64,",'')) file = open('img.jpeg', 'wb') file.write(imgData) file.close()
参考: https://stackoverflow.com/questions/33754935/read-a-base-64-encoded-image-from-memory-using-opencv-python-library/54205640