无法在 python 中保存 base64 jpg

Can't save base64 jpg in python

我有一个 base64 的 jpg,我想将它保存在我的项目文件夹中。 我试过

with open('image.jpg', 'wb') as f:
                f.write(img.decode('base64'))

但是 image.jpg 是 0KB。 img 就像 img= '/9j/4AAQSkZJRgABAQAAAQABAAD/...'

我该如何解决这个问题? 提前致谢!

如果您使用的是 .decode(),则假设图像字符串已经进行了字节编码。在这种情况下,您可以使用这样的代码:

import base64
with open('image.jpg', 'wb') as f:
    f.write(base64.decodebytes(img))

.decodebytes() 采用字节编码的 base64 字符串并将其转换回图像字节,然后您可以写入文件。