''' pip install pillow ''' from io import BytesIO from PIL import Image 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('zy.jpg', 'new_zy.jpg', target_size=100) print("图片压缩后的大小为(KB):", pic_size) if __name__ == '__main__': main()
标签:__,python,压缩,pic,path,byte,图片,quality,size From: https://www.cnblogs.com/boye169/p/18456514