python - 将 Base 64 字符串转换为 BytesIO

标签 python json flask base64 google-cloud-platform

感谢任何可以帮助解决这个问题的人,这是我的第一个问题,所以希望它不是非常明显。

我有一个作为 base64 字符串传递的图像(使用 slim 图像裁剪器)。我想将其转换为文件,然后将其作为 blob 发送到 Google Storage。

以前我只是发送如下文件

image = request.files.get('image')
client = _get_storage_client()
bucket = client.bucket(current_app.config['CLOUD_STORAGE_BUCKET'])
blob = bucket.blob(filename)

blob.upload_from_string(
    image.read(),
    content_type=content_type)

现在我正在处理下面的代码。

cropped_image = json.loads(request.form.get('slim[]'))
data = cropped_image['output']['image']

数据变量是一个字符串:

data = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBD...'

我不确定是否需要编码为 base64,从 base64 解码,将其转换为字节串然后编码/解码?

我试过使用 bytesIO 和 StringIO 发送它

image = BytesIO(data)
blob.upload_from_string(
    image.read(),
    content_type=content_type)

我上传了一张黑色图片,真的尽量不要在没有先研究的情况下提出问题,但这张让我难住了。

谢谢。

最佳答案

re.sub("data:image/jpeg;base64,", '', b64_str).decode("base64") 适用于 Python2。在 Py 2 中,str 实际上是 bytes

更新

from base64 import b64decode

with open("test.jpeg", 'wb') as f:
    f.write(b64decode(re.sub("data:image/jpeg;base64,", '', b64_str)))

# or

image = BytesIO(b64decode(re.sub("data:image/jpeg;base64", '', b64_str)))

关于python - 将 Base 64 字符串转换为 BytesIO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45685647/

相关文章:

python - 在 python 中使用列表创建 json 数组

python - 如何从 Python 代码中获取类和定义图?

python - 使用 dlopen 加载一个 .so 在 Python 中说它无法在同一目录中找到另一个

json - "The property cannot be found on this object. Verify that the property exists."属性肯定存在

python - 将 WTForms 与枚举一起使用

python - Flask-登录无法进行身份验证

python - numba.cuda.local.array() 的有效替代方案是什么,不像通过 to_device() 传递许多参数那么麻烦?

json - 如何使用 JSON 中的嵌套类型在 Swift 中表示字典

php - 我如何实现在我的应用程序上选择图像并将其发送到远程数据库(JSON+PHP)的可能性?

python - Flask:如何在应用程序上下文之外使用 url_for()?