当使用 PIL 删除 exif 时,文件大小增加而不是减少?

File size went up instead of down when exif removed with PIL?

没什么大不了的,但是为了了解正在发生的事情以避免将来出现问题...

我想知道为什么在删除 exif 数据后 jpg 的文件大小会增加。我以为它应该下降?

from PIL import Image

image = Image.open(fname)

name, ext = get_fname_ext(fname)

out_name = name + '_cleaned' + ext
out_abs = output_dir + "\" + out_name

image.save(out_abs)

之前的文件大小:192.65 KB

之后的文件大小:202.46 KB

差异:+9.82 KB

这里发生的是 PIL 重新压缩图像(源是 JPG,但它不是必须的,所以它被视为图像数据)。 safer/easier 依赖外部工具 exiftool, imagemagick or jpegtran. The answers on this related SO question 可能是一个很好的资源。

作为仅 PIL 的替代方案,您可以尝试 this answer 中的 python 片段是否适合您:

from PIL import Image

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

# 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')