最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Python的Pillow中如何压缩缩放图片且保持原图宽高比例

图片 crifan 2337浏览 0评论
折腾:
【未解决】Python中实现二进制数据的图片的压缩
期间,需要去知道如何缩小图片,且保持宽高比例
python binary image  compress
Python image library (PIL), how to compress image into desired file size? – Stack Overflow
知道了,缩放图片,可以用resize
以及尽量保证图片画质不要减低太多
但是还要搞清楚如何保持原始的宽高比例
image – How to perform JPEG compression in Python without writing/reading – Stack Overflow
image – Python File Compression – Stack Overflow
Using Python to Reduce JPEG and PNG Image File Sizes Without Loss of Quality
# The ‘quality’ option is ignored for PNG files
                img.save(filename, quality=90, optimize=True)
pil image compress
Python Image Optimization and Manipulation
http://python-pillow.github.io/
Pillow: the friendly PIL fork
Overview — Pillow (PIL Fork) 5.3.0 documentation
Tutorial — Pillow (PIL Fork) 5.3.0 documentation
https://pillow.readthedocs.io/en/5.3.x/handbook/tutorial.html#simple-geometry-transforms
out = im.resize((128, 128))
另外还要解决,压缩图片,缩放图片时,保持宽高比例
去看看resize是否有这种参数
Image Module — Pillow (PIL Fork) 5.3.0 documentation
Concepts — Pillow (PIL Fork) 5.3.0 documentation
python  pillow resize fit ratio
Does Python PIL resize maintain the aspect ratio? – Stack Overflow
image = Image.open(source_path)
image.thumbnail(size, Image.ANTIALIAS)
Create thumbnails
Image.thumbnail(size, resample=3)[source]
默认模式是:BICUBIC
去看:
Filters
https://pillow.readthedocs.io/en/stable/handbook/concepts.html#concept-filters
看不懂,不过看到:
貌似图片质量估计不错,所以就不去改默认模式了。
https://stackoverflow.com/questions/273946/how-do-i-resize-an-image-using-pil-and-maintain-its-aspect-ratio
建议还是用:
im.thumbnail(size, Image.ANTIALIAS)
不过发现是:宽高竟然全部都是250×250
-》之前设置的宽高?-》难道之前原图就是正方形的?
怀疑是:Image.ANTIALIAS 强制没有保留宽高比?
# resampling filters
NEAREST = NONE = 0
BOX = 4
BILINEAR = LINEAR = 2
HAMMING = 5
BICUBIC = CUBIC = 3
LANCZOS = ANTIALIAS = 1
后来证明:只是巧了,原图就是正方:(3543, 3543)
实际上是会保持原始比例的
从Pillow源码都可以看出来:
【总结】
最后没用resize,而是用thumbnail:
https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.thumbnail
代码:
IMAGE_COMPRESS_SIZE = (600, 600)
# imageFile.thumbnail(IMAGE_COMPRESS_SIZE, Image.ANTIALIAS)
imageFile.thumbnail(IMAGE_COMPRESS_SIZE, Image.LANCZOS)
效果:
可以将图片:
1.3MB的1114×572
压缩为:
307KB的600×308
在设置了600×600的前提下,基本上压缩率在:23%左右,足够好了。
而关于压缩后的图片质量:
通过调试发现:
# resampling filters
NEAREST = NONE = 0
BOX = 4
BILINEAR = LINEAR = 2
HAMMING = 5
BICUBIC = CUBIC = 3
LANCZOS = ANTIALIAS = 1
即:
LANCZOS = ANTIALIAS
所以改为:官网文档中提到的:LANCZOS
imageFile.thumbnail(IMAGE_COMPRESS_SIZE, Image.LANCZOS)
然后会:
保持尽量高的图片质量的,只不过压缩速度慢一点而已,此处不是问题。
所以就尽量用:Image.LANCZOS

转载请注明:在路上 » 【已解决】Python的Pillow中如何压缩缩放图片且保持原图宽高比例

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
87 queries in 0.160 seconds, using 22.10MB memory