Question

I wrote this code :

with Image.open(objective.picture.read()) as image:
    image_file = BytesIO()
    exifdata = image.info['exif']
    image.save(image_file, 'JPEG', quality=50, exif=exifdata)
    zf.writestr(zipped_filename, image_file)

Which is supposed to open the image stored in my model (this is in a Django application). I want to reduce the quality of the image file before adding it to the zipfile (zf). So I decided to work with BytesIO to prevent writing useless file on the disk. Though I'm getting an error here. It says :
embedded NUL character
Could someone help me out with this ? I don't understand what's going on.

Was it helpful?

Solution

Well I was kind of dumb. objective.picture.read() returns a byte string (really long byte string...) so I shouldn't have used Image but ImageFile.Parser() and feed that byte string to the parser so it can return an Image that I can work with. Here is the code :

from PIL import ImageFile
from io import BytesIO

p = ImageFile.Parser()
p.feed(objective.picture.read())
image = p.close()
image_file = BytesIO()
exifdata = image.info['exif']
image.save(image_file, 'JPEG', quality=50, exif=exifdata)
# Here zf is a zipfile writer
zf.writestr(zipped_filename, image_file.getvalue())

The close() actually returns the image parsed from the bytestring.
Here is the doc : The ImageFile Documentation

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top