base64转png图片
时间: 2023-11-15 19:57:59 浏览: 155
要将获取到的base64数据转为png格式的图片,可以按照以下步骤操作:
1. 使用base64模块的decodebytes方法将base64数据解码为二进制数据。
2. 使用open函数打开一个文件,以二进制写入模式("wb")打开。
3. 将解码后的二进制数据写入文件中。
4. 关闭文件。
具体代码如下:
```
import base64
# 假设获取到的base64数据为string
decoded = base64.decodebytes(string.encode("ascii"))
with open("XX.png", "wb") as fh:
fh.write(decoded)
```
如果要将base64数据转为jpg格式的图片,只需要将文件名中的".png"改为".jpg"即可。
另外,如果要将本地图片转为base64数据,可以按照以下步骤操作:
1. 使用open函数打开本地图片文件,以二进制读取模式("rb")打开。
2. 使用read方法读取文件内容,得到二进制数据。
3. 使用base64模块的b64encode方法将二进制数据编码为base64数据。
4. 使用open函数打开一个文件,以二进制写入模式("wb")打开。
5. 将编码后的base64数据写入文件中。
6. 关闭文件。
具体代码如下:
```
import base64
import os
# 假设本地图片路径为r'photo path\xx.png'
with open(r'photo path\xx.png','rb') as pngfile:
data = pngfile.read()
imgdata=base64.b64encode(data)
with open('xx.txt','wb') as fp:
fp.write(imgdata)
```
阅读全文
相关推荐












