2017-09-13 135 views
0

我想從網上獲取圖像並將其上傳到Amazon s3。雖然這樣做,我想檢查圖像尺寸。 我在Python 3以下代碼:將PIL圖像對象上傳到Amazon s3 python

from PIL import Image 
import requests 

# Get response 
response = requests.get(url, stream= True) 

# Open image 
im = Image.open(response.raw) 

# Get size 
size = im.size 

# Upload image to s3 
S3.Client.upload_fileobj(
    im, # This is what i am trying to upload 
    AWS_BUCKET_NAME, 
    key, 
    ExtraArgs={ 
     'ACL': 'public-read' 
    } 
) 

的問題是,PIL圖像對象不支持讀取。當我嘗試上傳PIL圖像對象im時出現以下錯誤。

ValueError: Fileobj must implement read 

它工作時,我只是嘗試上傳'response.raw',但我需要得到的圖像尺寸。如何將PIL圖像對象更改爲文件類對象?有沒有更容易的方式來獲得尺寸,同時仍然能夠上傳圖像到S3?

所以問題是,在獲取圖像的尺寸後,如何將圖像上傳到s3?

回答

3

而不是調用read(),以獲得該文件的內容回來,你的文件「保存」到任何一個真正的文件對象或像內存對象的文件。然後調用getValue()。

下面是一個示例函數,您可以將文件內容傳遞給它,打印出高度和寬度,然後以AWS客戶端put_object函數將接受的格式返回文件數據作爲Body參數。

from PIL import Image 
import io 

def modify_image(image, format): 
    pil_image = Image.open(image) 

    # Prints out (1280, 960) 
    print(pil_image.size) 

    in_mem_file = io.BytesIO() 

    # format here would be something like "JPEG". See below link for more info. 
    pil_image.save(in_mem_file, format=format) 
    return in_mem_file.getvalue() 

也有不同的寬度和高度屬性在這裏:http://pillow.readthedocs.io/en/3.4.x/reference/Image.html#attributes

查看更多有關文件格式,這裏http://pillow.readthedocs.io/en/3.4.x/handbook/image-file-formats.html

注:示例使用Python 3.6.1

0

您應該使用

response = requests.get(url, stream= True) 
f = io.BytesIO(response.content) 
image = Image.open(f) 
+0

這並不能改變什麼。圖像打開正常。當我想將圖像上傳到s3時,會出現問題。 – john

+0

您是否嘗試將'f'加載到aws?用'f'代替'im' – AndMar

+0

是的,我試過了。首先,'response'沒有一個名爲'read'的屬性,我假設你的意思是'response.raw.read()'。當我嘗試這樣做時,我上傳了一個空的file_obj,因爲當用Image.open()打開時,f已被清空。 – john