jupyter notebook 图片压缩批处理
import PIL.Image as Image
import os
#图片压缩批处理
#参数为文件路径和要保存的文件的路径
def compressImage(srcPath,dstPath):
#读取路径下的所有的文件
for filename in os.listdir(srcPath):
#目标路径不存在则创建目标路径
if not os.path.exists(dstPath):
#创建目标路径
os.makedirs(dstPath)
#拼接完整的文件或文件夹路径
srcFile = os.path.join(srcPath,filename)
dstFile = os.path.join(dstPath,filename)
#如果是文件就处理
if os.path.isfile(srcFile):
try:
#打开原图片缩小后保存
#可以用srcFile.endswith(".jpg")或者split,splitext等函数等针对特定文件压缩
sImg = Image.open(srcFile)
w,h =sImg.size
#设置压缩尺寸和选项,注意尺寸要括号
dImg =sImg.resize((int(w/2),int(h/2)),Image.ANTIALIAS)
dImg.save(dstFile)
print(dstFile+"success")
except Exception:
print(dstFile+" error!!!!!")
#如果文件夹就递归
if os.path.isdir(srcFile):
compressImage("I:\Camera","I:\picture")
package: import PIL.Image as Image import os
key:关键步骤和函数
- os.listdir(srcPath)#读取路径下的所有文件
- if not os.path.exists(dstPath):
os.makedirs(dstPath)#如果目标路径不存在创建目标路径存储文件 - srcFile = os.path.join(srcPath,filename)
dstFile = os.path.join(dstPath,filename)#拼接文件夹路径 - if os.path.isfile(srcFile):#判断是否为文件,是文件就压缩
- sImg = Image.open(srcFile)#打开图片
- w,h =sImg.size#读取图片高和宽
- dImg =sImg.resize((int(w/2),int(h/2)),Image.ANTIALIAS)#重新设置大小,设置压缩尺寸
- dImg.save(dstFile)#保存新的大小尺寸的图片到新文件路径
- if os.path.isdir(srcFile): compressImage(srcFile,dstFile)#若不是文件是文件夹,则递归转1