python对图片进行base64编码,互相转换
2021/8/25 14:35:59
本文主要是介绍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字符串:
要注意用读文件的方式读取图片,不能用 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
这篇关于python对图片进行base64编码,互相转换的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python