Python: Remove Exif info from images

2019-01-14 08:36发布

In order to reduce the size of images to be used in a website, I reduced the quality to 80-85%. This decreases the image size quite a bit, up to an extent.

To reduce the size further without compromising the quality, my friend pointed out that raw images from cameras have a lot of metadata called Exif info. Since there is no need to retain this Exif info for images in a website, we can remove it. This will further reduce the size by 3-10 kB.

But I'm not able to find an appropriate library to do this in my Python code. I have browsed through related questions and tried out some of the methods:

Original image: http://mdb.ibcdn.com/8snmhp4sjd75vdr27gbadolc003i.jpg

  1. Mogrify

    /usr/local/bin/mogrify -strip filename
    

    Result: http://s23.postimg.org/aeaw5x7ez/8snmhp4sjd75vdr27gbadolc003i_mogrify.jpg This method reduces the size from 105 kB to 99.6 kB, but also changed the color quality.

  2. Exif-tool

    exiftool -all= filename
    

    Result: http://s22.postimg.org/aiq99o775/8snmhp4sjd75vdr27gbadolc003i_exiftool.jpg This method reduces the size from 105 kB to 72.7 kB, but also changed the color quality.

  3. This answer explains in detail how to manipulate the Exif info, but how do I use it to remove the info?

Can anyone please help me remove all the extra metadata without changing the colours, dimensions, and other properties of an image?

4条回答
男人必须洒脱
2楼-- · 2019-01-14 08:52

For me, gexiv2 works fine:

#!/usr/bin/python3

from gi.repository import GExiv2

exif = GExiv2.Metadata('8snmhp4sjd75vdr27gbadolc003i.jpg')
exif.clear_exif()
exif.clear_xmp()
exif.save_file()

See also Exif manipulation library for python, which you linked, but didn't read all answers ;)

查看更多
唯我独甜
3楼-- · 2019-01-14 08:54
from PIL import Image

image_file = open('image_file.jpeg')
image = Image.open(image_file)

# next 3 lines strip exif
data = list(image.getdata())
image_without_exif = Image.new(image.mode, image.size)
image_without_exif.putdata(data)

image_without_exif.save('image_file_without_exif.jpeg')
查看更多
别忘想泡老子
4楼-- · 2019-01-14 09:07

You can try loading the image with the Python Image Lirbary (PIL) and then save it again to a different file. That should remove the meta data.

查看更多
闹够了就滚
5楼-- · 2019-01-14 09:14

You don't even need to do the extra steps @user2141737 suggested. Just opening it up with PIL and saving it again seems to do the trick just fine:

from PIL import Image
image = Image.open('path/to/image')
image.save('new/path/' + file_name)
查看更多
登录 后发表回答