将 Base 64 字符串转换为 BytesIO
Convert Base 64 String to BytesIO
感谢任何可以帮助解决这个问题的人,这是我的第一个问题,所以希望它不是非常明显。
我有一张图像作为 base64 字符串传递(使用 slim 图像裁剪器)。我想将其转换为文件,然后将其作为 blob 发送到 Google 存储。
之前我只是发送如下文件
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 解码,然后将其转换为字节串 encode/decode??
我试过使用 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)))
感谢任何可以帮助解决这个问题的人,这是我的第一个问题,所以希望它不是非常明显。
我有一张图像作为 base64 字符串传递(使用 slim 图像裁剪器)。我想将其转换为文件,然后将其作为 blob 发送到 Google 存储。
之前我只是发送如下文件
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 解码,然后将其转换为字节串 encode/decode??
我试过使用 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)))