【python】png转jpg(pillow)

项目场景

遇到一个png格式的图片,很大,有17MB。因为太大无法上传,所以就想在python中使用pillow库,将它转为小一点的jpg格式的图片。

安装模块

pip install pillow

转换代码

from PIL import Image
im = Image.open('test.png')
im = im.convert('RGB')
im.save('test.jpg', quality=95)

温馨提示

pngjpg其实也是一种图片压缩。save函数中quality参数指定图片质量,其取值范围是1~95,默认值是75

不建议使用默认值,因为它压缩图片太狠了,导致图片质量很差,和原图一比很明显就能看出差别。当然你对图片质量没什么要求的话可以用。

指定quality=95的时候,我发现压缩后的图片和原图基本上看不出什么差别。17MBpng图片能压缩为3MBjpg图片,这已经符合我的要求了。

引用参考

https://www.jianshu.com/p/66ccdb2db9c9
https://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.save
https://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.convert
原文地址:https://www.cnblogs.com/ghgxj/p/14219120.html