批量改变图片的后缀
改文件夹中图片的大小,输出到新的文件夹
- 完整代码
1 2 3 4 5 6 7 8 9 10
| from PIL import Image import os.path import glob def convertjpg(jpgfile,outdir,width=300,height=300): img=Image.open(jpgfile) new_img=img.resize((width,height),Image.BILINEAR) new_img.save(os.path.join(outdir,os.path.basename(jpgfile))) for jpgfile in glob.glob("C:\\Users\\fang\Desktop\IT\\*.bmp"): convertjpg(jpgfile,"C:\\Users\\fang\\Desktop\\IT2")
|
- 分段解析:
==Image是从PIL中引入的,不能直接import Image会找不到,pip也是只能下载PIL,无法只下载Image==
1 2
| for jpgfile in glob.glob("C:\\Users\\fang\Desktop\IT\\*.bmp"): convertjpg(jpgfile,"C:\\Users\\fang\\Desktop\\IT2")
|
重点:路径:“C:\Users\fang\Desktop\IT\*.bmp”
这样便可以操作到该文件中后缀为.bmp的全部图片
改文件夹中图片的后缀,并删除原来图片
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
#改文件夹中图片的后缀,并删除原来图片
import os
from PIL import Image
# bmp 转换为jpg def bmpToJpg(file_path): for fileName in os.listdir(file_path): # print(fileName) newFileName = fileName[0:fileName.find("_")]+".jpg" print(newFileName) im = Image.open(file_path+"\\"+fileName) im.save(file_path+"\\"+newFileName)
# 删除原来的位图 def deleteImages(file_path, imageFormat): command = "del "+file_path+"\\*."+imageFormat os.system(command)
def main(): file_path = "C:\\Users\\fangj\\Desktop\\IT2" bmpToJpg(file_path) deleteImages(file_path, "bmp")
if __name__ == '__main__': main()
|