如何将base64图片转换为图片并保存到文件系统

How to convert a base64 image to an image and save it to the file system

我有一个字符串:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAjwAAAJbCAIAAABvnNkvAAAACXBIWXM и т.д.

已满:https://pastebin.com/tfDThBnE

如何将此图片转换为png和jpg并保存在文件系统中?

from PIL import Image
import base64
from io import BytesIO

data = 'copy_your_raw_data_here'
# you need to remove the prefix 'data:image/png;base64,'

bytes_decoded = base64.b64decode(data)


img = Image.open(BytesIO(bytes_decoded))
img.show()

# to jpg
out_jpg = img.convert("RGB")

# save file
out_jpg.save("saved_img.jpg")

如果您没有 PIL(Pillow) 库,请确保先安装它。

pip install pillow

它是一个 python imgae 处理程序包。