from PIL import Image
foo = Image.open('path/to/image.jpg') # My image is a 200x374 jpeg that is 102kb large
foo.size # (200, 374)
# downsize the image with an ANTIALIAS filter (gives the highest quality)
foo = foo.resize((160,300),Image.ANTIALIAS)
foo.save('path/to/save/image_scaled.jpg', quality=95) # The saved downsized image size is 24.8kb
foo.save('path/to/save/image_scaled_opt.jpg', optimize=True, quality=95) # The saved downsized image size is 22.9kb
现在尝试将它降低到5kb 到10kb,您可以在保存选项中更改质量值。
Using a quality of 85 instead of 95 in this case would yield:
未优化: 15.1 kb
优化: 14.3 kb
使用质量为75(如果省略参数,则默认为75)将产生:
未优化: 11.8 kb
优化: 11.2 kb
假设你有一个名为 Book 的模型,在它上面有一个名为‘ cover _ pic’的字段,
in that case, you can do the following to compress the image:
from PIL import Image
b = Book.objects.get(title='Into the wild')
image = Image.open(b.cover_pic.path)
image.save(b.image.path,quality=20,optimize=True)