Features
- Jpg image size batch modify the current folder to set
- The picture modified to move
new_img
the file folder
Import library
from PIL import Image # 处理图片模块
import os
import shutil # 移动文件模块
If you do not install the appropriate library in advance.
Definition of a function for processing image size
def smaller_img(x, y, path): # x,y用来传入尺寸,path用来传入路径
old_img = Image.open(path)
img_deal = old_img.resize((x, y), Image.ANTIALIAS) # 转换图片
img_deal = img_deal.convert('RGB') # 保存为jpg格式才需要
img_deal.save('新的文件名')
Traverse the file path to the current folder
now_path = os.getcwd()
new_path = os.mkdir(now_path + '\\' + 'new_img') # 创建一个名为new_img的文件夹
for file_name in os.listdir(now_path):
files_path = now_path + '\\' + file_name
print(files_path) # 输出当前目录下所有的文件的绝对路径
The new file picture modified to create a folder to move
I use awkward, with a string of judgment way to determine whether the modified image files.
shutil
Module Reference Links
for move_name in os.listdir(now_path):
move_path = now_path + '\\' + move_name
if 'switch' in move_path:
shutil.move(move_path,new_dir) # shutil.move(文件/目录 , 目录)
else:
print(move_path, '无须移动')
The integration of these functions together
from PIL import Image
import os
import shutil
x = input('请输入需要修改的尺寸,长:')
x = int(x)
y = input('请输入需要修改的尺寸,高:')
y = int(y)
now_path = os.getcwd()
new_path = os.mkdir(now_path + '\\' + 'new_img')
new_dir = now_path + '\\' + 'new_img'
# 修改图片大小
def smaller_img(x, y, path):
path = str(path)
old_img = Image.open(path)
img_deal = old_img.resize((x, y), Image.ANTIALIAS)
img_deal = img_deal.convert('RGB')
img_deal.save('switch_' + file_name)
# 遍历文件夹下的文件,并判断是否是JPG文件
for file_name in os.listdir(now_path):
files_path = now_path + '\\' + file_name
if 'jpg' in files_path:
smaller_img(x, y, files_path)
# 遍历文件来判断是否是转换后的jpg文件
for move_name in os.listdir(now_path):
move_path = now_path + '\\' + move_name
if 'switch' in move_path:
shutil.move(move_path,new_dir)
else:
print(move_path, '无须移动')
print(file_name, 'switch success')
else:
print(file_name, 'is not img')
Conclusion
Please indicate the wrong place, please a lot of criticism