Scenario
I use a formData form to upload an image via ajax which is then added to a MongoDB GridFS database.
This was working:
my_image = request.files.my_image
raw = my_image.file.read()
fs.put(raw)
Desired Behaviour
I want to resize the image with Pillow before adding to GridFS.
What I Tried
I changed the above to:
my_image = request.files.my_image
raw = Image.open(my_image.file.read())
raw_resized = raw.resize((new_dimensions))
fs.put(raw_resized)
Actual Behaviour
I am now getting 500 errors. Tail shows:
TypeError: file() argument 1 must be encoded string without NULL bytes, not str
Question
How do I properly handle the Pillow image object so that I can add it to GridFS?
Troubelshooting
This is still unresolved, but I'm just adding my attempts to understand what is happening with file types etc at different stages of the process by using the interpretor:
>>> my_image = open("my_great_image.jpg")
>>> my_image
<open file 'my_great_image.jpg', mode 'r' at 0x0259CF40>
>>> type(my_image)
<type 'file'>
>>> my_image_read = my_image.read()
>>> my_image_read
# lots of image data
>>> type(my_image_read)
<type 'str'>
>>> my_pil_image = Image.open("my_great_image.jpg")
>>> my_pil_image
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=400x267 at 0x2760CD8>
>>> type(my_pil_image)
<type 'instance'>
So from this I think I can deduce that, originally, GridFS was accepting of the string version of the image generated from the read()
method.
So I think I need to somehow make the Pillow image object a string in order to get it into GridFS.