2014-09-02 106 views
2

我想要一個圖像然後把它變成一個對象Python理解然後上傳。AttributeError:用Python讀取

這是我曾嘗試:

# Read the image using .count to get binary 
image_binary = requests.get(
    "http://danealva143.files.wordpress.com/2014/03/2012-08-girls-920-26.jpg").content 


string_buffer = io.BytesIO() 
string_buffer.write(image_binary) 
string_buffer.seek(0) 

files = {} 
files['image'] = Image.open(string_buffer) 
payload = {} 

results = requests.patch(url="http://127.0.0.1:8000/api/profile/94/", data=payload, files=files) 

我得到這個錯誤:

File "/Users/user/Documents/workspace/test/django-env/lib/python2.7/site-packages/PIL/Image.py", line 605, in __getattr__ 
    raise AttributeError(name) 
AttributeError: read 

爲什麼?

回答

3

您不能發佈PIL.Image對象; requests需要一個文件對象。

如果您沒有更改圖像,則將數據加載到Image對象中也沒有意義。只需發送image_binary數據,而不是:

files = {'image': image_binary} 
results = requests.patch(url="http://127.0.0.1:8000/api/profile/94/", data=payload, files=files) 

您可能要包括的MIME類型的圖像二值:

image_resp = requests.get(
    "http://danealva143.files.wordpress.com/2014/03/2012-08-girls-920-26.jpg") 
files = { 
    'image': (image_resp.url.rpartition('/')[-1], image_resp.content, image_resp.headers['Content-Type']) 
} 

如果你真的想處理圖像,你首先必須將圖像保存回一個文件對象:

img = Image.open(string_buffer) 
# do stuff with `img` 

output = io.BytesIO() 
img.save(output, format='JPEG') # or another format 
output.seek(0) 

files = { 
    'image': ('somefilename.jpg', output, 'image/jpeg'), 
} 

Image.save() method接受一個任意文件對象寫,但因爲在這種情況下沒有文件名取格式,您必須手動指定要寫入的圖像格式。從supported image formats挑選。

+0

只是在這裏嘗試,但如果我想改變圖像怎麼辦。我是否需要將它恢復爲二進制文件,即保存它? – Prometheus 2014-09-02 10:16:21

+0

@Sputnik:增加了關於如何將PIL圖像保存到「BytesIO」內存中文件對象的信息。 – 2014-09-02 10:24:05

+0

謝謝,幫助很多:) – Prometheus 2014-09-02 10:26:55