感谢任何可以帮助解决这个问题的人,这是我的第一个问题,所以希望它不是非常明显。
我有一个作为 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/