3

I am trying to strip out exif data on an uploaded image before continuing to do some other processing to it before saving to the server.

I am using piexif as in this answer to strip out the exif metadata. However, piexif.insert() documentation requires the path to the image being modified. Can piexif be used to write to a file in memory?

PIL is also documented to strip out exif data. Since I am using PIL anyways, I'd rather have a pure PIL approach.

def modifyAndSaveImage():
    # Get the uploaded image as an InMemoryUploadedFile
    i = form.cleaned_data['image']

    # Use piexif to remove exif in-memory?
    #exif_bytes = piexif.dump({})
    #piexif.insert(exif_bytes, i._name)  # What should the second parameter be?

    # continue using i...
    im = Image.open(i)
    buffer = BytesIO()
    im.save(fp=buffer, format='JPEG', quality=95)

    return ContentFile(buffer.getvalue())

PIL's save method seems to be applying the exif data to the image, than saving it without the exif (applies rotation to the raw image). Or is this caused by the BytesIO buffer?

user3750325
  • 1,502
  • 1
  • 18
  • 37

1 Answers1

0

If you load the file with PIL and save it, it'll strip the EXIF;

from PIL import Image

image = Image.open(form.cleaned_data['image'])

image.save('my_images/image.jpg')

If you have an issue with any data still present, you could also try to create a whole new image like this;

from PIL import Image

image = Image.open(form.cleaned_data['image'])

image_data = list(image.getdata())

new_image = Image.new(image.mode, image.size)
new_image.putdata(image_data)
new_image.save('my_images/image.jpg')

docs on Image are here

markwalker_
  • 12,078
  • 7
  • 62
  • 99
  • I was actually passing this into PIL and doing an Image.save in the following steps. While the exif is stripped, it looks like the rotation is applied to the image. I'm thinking it has to do with my use of BytesIO and ContentBuffer. Question updated with this code. – user3750325 Sep 14 '20 at 15:38