2014-09-02 108 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