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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With