AttributeError:在Python中读取

AttributeError:在Python中读取,python,python-2.7,python-imaging-library,python-requests,Python,Python 2.7,Python Imaging Library,Python Requests,我试图得到一个图像,然后把它变成一个对象,然后上传 这就是我尝试过的: # 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(ima

我试图得到一个图像,然后把它变成一个对象,然后上传

这就是我尝试过的:

# 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

为什么?

您不能发布
PIL.Image
对象<代码>请求需要一个文件对象

如果不更改图像,则也没有必要将数据加载到
图像
对象中。只需发送
图像\u二进制数据即可:

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'),
}

获取要写入的任意文件对象,但由于在这种情况下没有可从中获取格式的文件名,因此必须手动指定要写入的图像格式。从中选择。

只是在这里进行试验,但如果我想更改图像,该怎么办。我是否需要将其转换回二进制文件,即保存它?@Sputnik:添加了有关如何将PIL图像保存回
BytesIO
内存文件对象的信息。谢谢,帮助很大:)