1. import base64, io, os, random
    2. from PIL import Image, ImageFile
    3. # 压缩图片文件
    4. def compress_image(index):
    5. """不改变图片尺寸压缩到指定大小
    6. :param outfile: 压缩文件保存地址
    7. :param mb: 压缩目标,KB
    8. :param step: 每次调整的压缩比率
    9. :param quality: 初始压缩比率
    10. :return: 压缩文件地址,压缩文件大小
    11. """
    12. outfile = os.getcwd() + f'\\{index}.png'
    13. mb = 190
    14. quality = 85
    15. k = 0.9
    16. o_size = os.path.getsize(outfile) // 1024
    17. print('压缩前得图片大小------' + str(o_size))
    18. if o_size <= mb:
    19. return reanme(index)
    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. print('压缩后得图片大小------' + str(o_size))
    32. reanme(index)
    33. return outfile
    34. def reanme(index):
    35. ran_name = 'img_' + str(random.random()).replace('.', '') + '_' + str(random.randint(1, 100000))
    36. img_path = os.getcwd()
    37. img_list = os.listdir(img_path)
    38. for img in img_list:
    39. if img.endswith('.png') & img.startswith(f'{index}'):
    40. src = os.path.join(os.path.abspath(img_path), img) # 原先的图片名字
    41. dst = os.path.join(os.path.abspath(img_path), ran_name + img) # 根据自己的需要重新命名,可以把'E_' + img改成你想要的名字
    42. os.rename(src, dst) # 重命名,覆盖原先的名字
    43. # 压缩base64的图片
    44. def compress_image_bs4(b64, mb=190, k=0.9):
    45. """不改变图片尺寸压缩到指定大小
    46. :param outfile: 压缩文件保存地址
    47. :param mb: 压缩目标,KB
    48. :param step: 每次调整的压缩比率
    49. :param quality: 初始压缩比率
    50. :return: 压缩文件地址,压缩文件大小
    51. """
    52. f = base64.b64decode(b64)
    53. with io.BytesIO(f) as im:
    54. o_size = len(im.getvalue()) // 1024
    55. if o_size <= mb:
    56. return b64
    57. im_out = im
    58. while o_size > mb:
    59. img = Image.open(im_out)
    60. x, y = img.size
    61. out = img.resize((int(x * k), int(y * k)), Image.ANTIALIAS)
    62. im_out.close()
    63. im_out = io.BytesIO()
    64. out.save(im_out, 'jpeg')
    65. o_size = len(im_out.getvalue()) // 1024
    66. b64 = base64.b64encode(im_out.getvalue())
    67. im_out.close()
    68. return str(b64, encoding='utf8')
    69. if __name__ == "__main__":
    70. # 获取图片路径
    71. for i in range(0, 6):
    72. compress_image(i)
    73. print('----------------')
    74. print(f'第{i}张压缩成功!!')