python图片压缩
时间: 2023-08-19 18:13:07 浏览: 116
在Python中,有多种方法可以进行图片压缩。其中两种常用的方法是使用OpenCV和Pillow库。
使用OpenCV进行图片压缩的核心思路是循环降低图片质量,直至图片质量大小符合目标质量后退出循环。可以使用以下代码实现图片压缩:
```python
import cv2
import numpy as np
def pic_compress(pic_path, out_path, target_size=199, quality=90, step=5, pic_type='.jpg'):
# 读取图片bytes
with open(pic_path, 'rb') as f:
pic_byte = f.read()
img_np = np.frombuffer(pic_byte, np.uint8)
img_cv = cv2.imdecode(img_np, cv2.IMREAD_ANYCOLOR)
current_size = len(pic_byte) / 1024
print("图片压缩前的大小为(KB):", current_size)
while current_size > target_size:
pic_byte = cv2.imencode(pic_type, img_cv, [int(cv2.IMWRITE_JPEG_QUALITY), quality])[1]
if quality - step < 0:
break
quality -= step
current_size = len(pic_byte) / 1024
# 保存图片
with open(out_path, 'wb') as f:
f.write(pic_byte)
return len(pic_byte) / 1024
def main():
pic_size = pic_compress('test.jpg', 'new_test.jpg', target_size=100)
print("图片压缩后的大小为(KB):", pic_size)
if __name__ == '__main__':
main()
```
另一种常用的方法是使用Pillow库进行图片压缩。Pillow库的核心思路也是循环降低图片质量,直至图片质量大小符合目标质量后退出循环。可以使用以下代码实现图片压缩:
```python
from PIL import Image
from io import BytesIO
def pic_compress(pic_path, out_path, target_size, quality=90, step=5):
# 读取图片bytes
with open(pic_path, 'rb') as f:
pic_byte = f.read()
current_size = len(pic_byte) / 1024
print("图片压缩前的大小为(KB):", current_size)
while current_size > target_size:
img = Image.open(BytesIO(pic_byte))
buf = BytesIO()
img.save(buf, format=img.format, quality=quality)
pic_byte = buf.getvalue()
if quality - step < 0:
break
quality -= step
current_size = len(pic_byte) / 1024
# 保存图片
with open(out_path, 'wb') as f:
f.write(pic_byte)
return len(pic_byte) / 1024
def main():
pic_size = pic_compress('test.jpg', 'new_test.jpg', target_size=100)
print("图片压缩后的大小为(KB):", pic_size)
if __name__ == '__main__':
main()
```
这两种方法都可以实现图片压缩,但是使用OpenCV进行压缩可能会更加保真。
阅读全文