2025年3月24日 星期一 甲辰(龙)年 月廿三 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

python --压缩图片不改变图片尺寸

时间:08-14来源:作者:点击数:35

python --压缩图片不改变图片尺寸

方法1

  • from PIL import Image
  • import os
  • def compress_image(infile, outfile, quality=50):
  • """
  • 压缩图片文件大小
  • :param infile: 原始图片文件
  • :param outfile: 压缩后图片文件
  • :param quality: 压缩质量,默认为50
  • :return: 无
  • """
  • try:
  • with Image.open(infile) as im:
  • im.save(outfile, quality=quality)
  • except Exception as e:
  • print(f"压缩图片失败:{e}")
  • return
  • if __name__ == '__main__':
  • infile = 'test.jpg'
  • outfile = 'test_compressed.jpg'
  • compress_image(infile, outfile, quality=50)
  • print(f"压缩前文件大小:{os.path.getsize(infile)}")
  • print(f"压缩后文件大小:{os.path.getsize(outfile)}")

在这个示例中,我们使用了Pillow库中的Image类来打开原始图片文件,然后使用save方法将其保存为压缩后的图片文件。quality参数指定了压缩质量,值越小,压缩后的图片文件大小越小。最后,我们使用os.path.getsize函数来获取压缩前和压缩后的文件大小。

方法2

不改变图片尺寸

  • from PIL import Image
  • import os
  • def get_size(file):
  • # 获取文件大小:KB
  • size = os.path.getsize(file)
  • return size / 1024
  • def get_outfile(infile, outfile):
  • if outfile:
  • return outfile
  • dir, suffix = os.path.splitext(infile)
  • outfile = '{}-out{}'.format(dir, suffix)
  • return outfile
  • def compress_image(infile, outfile='', mb=150, step=10, quality=80):
  • """不改变图片尺寸压缩到指定大小
  • :param infile: 压缩源文件
  • :param outfile: 压缩文件保存地址
  • :param mb: 压缩目标,KB
  • :param step: 每次调整的压缩比率
  • :param quality: 初始压缩比率
  • :return: 压缩文件地址,压缩文件大小
  • """
  • o_size = get_size(infile)
  • print(o_size)
  • if o_size <= mb:
  • return infile
  • outfile = get_outfile(infile, outfile)
  • while o_size > mb:
  • im = Image.open(infile)
  • # 出现 OSError: cannot write mode RGBA as JPEG 错误时加入下方语句
  • im = im.convert("RGB")
  • im.save(outfile, quality=quality)
  • if quality - step < 0:
  • break
  • quality -= step
  • o_size = get_size(outfile)
  • return outfile, get_size(outfile)
  • if __name__ == '__main__':
  • print(compress_image(r'C:\Users\Administrator\Desktop\100000.png',
  • r'C:\Users\Administrator\Desktop\888.jpg'))

修改图片尺寸,如果同时有修改尺寸和大小的需要,可以先修改尺寸,再压缩大小

  • def resize_image(infile, outfile='', x_s=1376):
  • """修改图片尺寸
  • :param infile: 图片源文件
  • :param outfile: 重设尺寸文件保存地址
  • :param x_s: 设置的宽度
  • :return:
  • """
  • im = Image.open(infile)
  • x, y = im.size
  • y_s = int(y * x_s / x)
  • out = im.resize((x_s, y_s), Image.ANTIALIAS)
  • outfile = get_outfile(infile, outfile)
  • out.save(outfile)
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐