2017-08-15 73 views
0

感谢任何能够帮助解决这个问题的人,我的第一个问题是希望它不是非常明显。将Base 64字符串转换为BytesIO

我有一个图像被作为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) 

和我上传了黑色画面,真正尝试不问不研究的第一个问题,但是这其中有我难住了。

谢谢。

+0

的参数'upload_from_string'是在第二种情况下作为第一相同。从'data'创建的变量'image'在调用'upload_from_string'时没有使用。是对的吗? –

+0

在第一个示例中,我传递从Web表单上传的filestorage。 – Solutionist

+0

我已经尝试将数据变量发送到upload_from_string,并获得与使用bytesIO或StringIO相同的结果。 – Solutionist

回答

0

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

UPDATE

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

我该如何用数据变量来保存字符串?喜欢这个? 're.sub(data,'',b64_str).decode(“base64”)' – Solutionist

+0

@Solutionist用你的数据变量替换'b64_str'来保存字符串。 – stamaimer

+0

我得到以下'fixeddata = re.sub(“data:image/jpeg; base64”,'',data.decode(“base64”)) AttributeError:'str'对象没有属性'decode'' – Solutionist