infile = 'C:\Users\29903\Desktop\《玩具总动员3》.jpg' import os def compress_image(infile, outfile='C:\\Users\29903\Desktop\《玩具总动员3》2.jpg', mb=1500, step=10, quality=80): """不改变图片尺寸压缩到指定大小 :param infile: 压缩源文件 :param outfile: 压缩文件保存地址 param mb: 压缩目标,KB :param step: 每次调整的压缩比率 :param quality: 初始压缩比率 :return: 压缩文件地址,压缩文件大小""" n = 1024 o_size = os.path.getsize(infile) / n if o_size <= mb: return infile outfile = get_outfile(infile,outfile) while o_size > mb: im = Image.open(infile) im.save(outfile, quality = quality) if quality - step < 0: break quality -= step o_size = get_size(outfile) return outfile,get_size(outfile) compress_image(infile)以上代码有错吗
时间: 2023-12-10 13:41:36 浏览: 71
commons-compress-1.18.zip
有几个问题需要修正:
1. 在 Windows 系统下,文件路径需要使用双反斜杠 `\\` 或者单斜杠 `/`,不能使用单反斜杠 `\`,因为单反斜杠在 Python 中是转义符号;
2. `get_outfile` 函数没有定义,需要先定义该函数;
3. `Image` 模块没有被导入,需要先导入该模块。
修正后的代码如下:
```python
import os
from PIL import Image
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=None, mb=1500, step=10, quality=80):
"""不改变图片尺寸压缩到指定大小
:param infile: 压缩源文件
:param outfile: 压缩文件保存地址
:param mb: 压缩目标,KB
:param step: 每次调整的压缩比率
:param quality: 初始压缩比率
:return: 压缩文件地址,压缩文件大小
"""
n = 1024
o_size = os.path.getsize(infile) / n
if o_size <= mb:
return infile
outfile = get_outfile(infile,outfile)
while o_size > mb:
im = Image.open(infile)
im.save(outfile, quality=quality)
if quality - step < 0:
break
quality -= step
o_size = os.path.getsize(outfile) / n
return outfile, o_size
infile = r'C:\Users\29903\Desktop\《玩具总动员3》.jpg'
compress_image(infile)
```
阅读全文