python - base64转图片

折腾了base64转png弄了很久,使用以下代码进行转换后图片一直打不开

import base64

imgData = "data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD后面省略"
imgData = imgData.split(",")[1]
imgData = base64.b64decode(imgData)
with open("test.png", "wb") as f:
    f.write(imgData)

最后才发现是因为自己要转换的这个base64里面带有%2B,所以需要先将%2B这些先进行反转义

import urllib
import base64

imgData = "data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD后面省略"
imgData = imgData.split(",")[1]
imgData = urllib.parse.unquote(imgData)
imgData = base64.b64decode(imgData)
with open("test.png", "wb") as f:
    f.write(imgData)

posted @ 2023-08-19 19:03  wstong  阅读(727)  评论(0编辑  收藏  举报