PIL Image resize 在不希望压缩图像时压缩图像
PIL Image resize compresses the image when is not expected to
我有以下具有覆盖保存方法的 Django 模型:
class Photo(models.Model):
image = models.ImageField(upload_to=get_file_path, blank=False, null=False)
def save(self, *args, **kwargs):
"""
Override save method to resize uploaded photo images to max_size.
"""
if not self.id and not self.image:
return
super(Photo, self).save(*args, **kwargs)
resized_image = Image.open(self.image)
resized_image = resized_image.resize(settings.PHOTO_CONFIG['max_size'], Image.ANTIALIAS)
resized_image.save(self.image.path)
以及 settings.py 中的以下配置:
PHOTO_CONFIG = {
'max_size': (900, 900),
}
现在,当我上传大小正好为 900x900 (500 kb) 的 JPG 时,上传的 JPG 被压缩到大约 100kb。两者都是 900x900 和 72 dpi 分辨率。
这是怎么发生的,为什么会发生?
这可能有多种原因,但简而言之,这可能是因为默认保存参数不是用于创建原始图像的参数。
它可能是:
- 原始图像的质量更高。 Pillow 的默认质量是 75(它可以从 1 到 95(最佳))。较低的质量有时会减小尺寸。
- 原始图像有 EXIF 数据(例如来自相机)或 ICC 配置文件。默认情况下,Pillow 不保存任何 EXIF 数据或 ICC 配置文件。
查看 the complete list of options of the save method for JPEG file 和它们的默认值,您应该找出哪一个与您的情况不同。
我有以下具有覆盖保存方法的 Django 模型:
class Photo(models.Model):
image = models.ImageField(upload_to=get_file_path, blank=False, null=False)
def save(self, *args, **kwargs):
"""
Override save method to resize uploaded photo images to max_size.
"""
if not self.id and not self.image:
return
super(Photo, self).save(*args, **kwargs)
resized_image = Image.open(self.image)
resized_image = resized_image.resize(settings.PHOTO_CONFIG['max_size'], Image.ANTIALIAS)
resized_image.save(self.image.path)
以及 settings.py 中的以下配置:
PHOTO_CONFIG = {
'max_size': (900, 900),
}
现在,当我上传大小正好为 900x900 (500 kb) 的 JPG 时,上传的 JPG 被压缩到大约 100kb。两者都是 900x900 和 72 dpi 分辨率。
这是怎么发生的,为什么会发生?
这可能有多种原因,但简而言之,这可能是因为默认保存参数不是用于创建原始图像的参数。
它可能是:
- 原始图像的质量更高。 Pillow 的默认质量是 75(它可以从 1 到 95(最佳))。较低的质量有时会减小尺寸。
- 原始图像有 EXIF 数据(例如来自相机)或 ICC 配置文件。默认情况下,Pillow 不保存任何 EXIF 数据或 ICC 配置文件。
查看 the complete list of options of the save method for JPEG file 和它们的默认值,您应该找出哪一个与您的情况不同。