图像文件压缩。使用PIL库对图像进行等比例压缩,无论压缩前文件大小如何,压缩后文件大小小于10KB。
时间: 2023-12-02 08:59:09 浏览: 40
可以使用PIL库中的resize()方法对图像进行等比例压缩,然后使用save()方法将压缩后的图像保存为文件。
以下是一个示例代码,其中img_path是原始图像文件路径,compressed_path是压缩后的图像文件路径,quality是压缩质量(0-100):
```python
from PIL import Image
import os
img_path = "example.jpg"
compressed_path = "example_compressed.jpg"
quality = 50
img = Image.open(img_path)
width, height = img.size
# 计算等比例压缩后的大小
ratio = min(float(10240) / float(os.path.getsize(img_path)), 1)
new_width = int(width * ratio)
new_height = int(height * ratio)
# 等比例压缩图像
img = img.resize((new_width, new_height), Image.ANTIALIAS)
# 保存压缩后的图像
img.save(compressed_path, optimize=True, quality=quality)
```
在这个示例中,我们通过计算原始图像文件大小和目标大小之间的比例来确定压缩比例。如果原始文件小于10KB,则不进行压缩。我们还可以使用quality参数来调整压缩质量以控制压缩后文件的大小。