1. import base64
    2. import io
    3. import os
    4. from PIL import Image
    5. from PIL import ImageFile
    6. # 压缩图片文件
    7. def compress_image(outfile, mb=1024, quality=85, k=0.9):
    8. """不改变图片尺寸压缩到指定大小
    9. :param k:
    10. :param outfile: 压缩文件保存地址
    11. :param mb: 压缩目标,KB
    12. :param step: 每次调整的压缩比率
    13. :param quality: 初始压缩比率
    14. :return: 压缩文件地址,压缩文件大小
    15. """
    16. o_size = os.path.getsize(outfile) // 1024
    17. print(o_size, mb)
    18. if o_size <= mb:
    19. return outfile
    20. ImageFile.LOAD_TRUNCATED_IMAGES = True
    21. while o_size > mb:
    22. im = Image.open(outfile)
    23. x, y = im.size
    24. out = im.resize((int(x * k), int(y * k)), Image.ANTIALIAS)
    25. try:
    26. out.save(outfile, quality=quality)
    27. except Exception as e:
    28. print(e)
    29. break
    30. o_size = os.path.getsize(outfile) // 1024
    31. return outfile
    32. # 压缩base64的图片
    33. def compress_image_bs4(b64, mb=190, k=0.9):
    34. """不改变图片尺寸压缩到指定大小
    35. :param outfile: 压缩文件保存地址
    36. :param mb: 压缩目标,KB
    37. :param step: 每次调整的压缩比率
    38. :param quality: 初始压缩比率
    39. :return: 压缩文件地址,压缩文件大小
    40. """
    41. f = base64.b64decode(b64)
    42. with io.BytesIO(f) as im:
    43. o_size = len(im.getvalue()) // 1024
    44. if o_size <= mb:
    45. return b64
    46. im_out = im
    47. while o_size > mb:
    48. img = Image.open(im_out)
    49. x, y = img.size
    50. out = img.resize((int(x * k), int(y * k)), Image.ANTIALIAS)
    51. im_out.close()
    52. im_out = io.BytesIO()
    53. out.save(im_out, 'jpeg')
    54. o_size = len(im_out.getvalue()) // 1024
    55. b64 = base64.b64encode(im_out.getvalue())
    56. im_out.close()
    57. return str(b64, encoding='utf8')
    58. if __name__ == "__main__":
    59. for img in os.listdir('./out_img'):
    60. compress_image(outfile='./out_img/' + str(img)[0:-4] + '.png')
    61. print('完')