【问题标题】:Convert Base 64 String to BytesIO将 Base 64 字符串转换为 BytesIO
【发布时间】:2018-01-22 22:46:48
【问题描述】:

感谢任何可以提供帮助的人,这是我的第一个问题,所以希望它不是很明显。

我有一个作为 base64 字符串传递的图像(使用苗条图像裁剪器)。我想将其转换为文件,然后将其作为 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 解码,将其转换为字节串,然后编码/解码??

我尝试过使用 bytesIO 和 StringIO 原样发送它

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

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

谢谢。

【问题讨论】:

  • upload_from_string 的参数在第二种情况下与第一种情况相同。您从data 创建的变量image 不会在对upload_from_string 的调用中使用。对吗?
  • 在第一个示例中,我正在传递从 Web 表单上传的文件存储。
  • 我已尝试将数据变量发送到upload_from_string 并获得与使用bytesIO 或StringIO 相同的结果。

标签: python json flask base64 gcp


【解决方案1】:

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)))

【讨论】:

  • 如何使用包含字符串的数据变量来执行此操作?像这样? re.sub(data, '', b64_str).decode("base64")
  • @Solutionist 将 b64_str 替换为包含字符串的数据变量。
  • 我收到以下fixeddata = re.sub("data:image/jpeg;base64", '', data.decode("base64")) AttributeError: 'str' object has no attribute 'decode'
  • 道歉fixeddata = re.sub("data:image/jpeg;base64", '', data).decode("base64") AttributeError: 'str' object has no attribute 'decode'
  • 尝试将数据转换为字节。 re.sub("data:image/jpeg;base64", '', bytes(data)).decode("base64").
猜你喜欢
  • 2015-08-09
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 2013-07-09
  • 1970-01-01
  • 2017-10-24
  • 2011-07-20
  • 1970-01-01
相关资源
最近更新 更多