2017-08-15 91 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