3

I'm trying to get an image then turn it into an object Python understands then upload.

This is what I have tried:

# 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)

I get this error:

  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

Why?

1 Answer 1

3

You cannot post a PIL.Image object; requests expects a file object.

If you are not altering the image, there is no point in loading the data into an Image object either. Just send the image_binary data instead:

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

You may want to include the mime-type for the image binary:

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

If you actually wanted to manipulate the image, you'll first have to save the image back to a file object:

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

The Image.save() method takes an arbitrary file object to write to, but because there is no filename in that case to take the format from, you'll have to manually specify the image format to write. Pick from the supported image formats.

Sign up to request clarification or add additional context in comments.

2 Comments

Just experimenting here, but what if i wanted to change the image. Would I need to turn it back into binary i.e. save it?
@Sputnik: added info on how to save back the PIL image to a BytesIO in-memory file object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.