图片批量缩放工具
使用python实现的图片批量缩放工具,能够多选图片然后统一缩放到指定的宽度与高度。
图片格式支持:jpg, jpeg, png, gif
有两种输出模式,改名后输出到原图片路径,或者在程序所在路径新建输出文件夹后用图片原文件名输出。
注:打包为exe请使用虚拟环境。
## -*- coding: utf-8 -*-
# written by starvapour, 21/5/2021
from PIL.Image import ANTIALIAS, BILINEAR, BICUBIC, NEAREST, open, fromarray
from os.path import split, splitext, exists
from os import mkdir
from tkinter import Tk, filedialog
from time import sleep
from imageio import mimread, mimsave
# 如果选择在输出文件夹输出,那么使用此路径作为输出文件夹
output_path = "resize_output"
# 用于快速缩放图片分辨率
print("请选择需要缩放的图片:")
root = Tk()
root.withdraw()
img_paths = filedialog.askopenfilenames(filetypes=[('图片文件', ('.jpg', '.jpeg', '.png', '.bmp', ".gif")), ('所有文件', '*')])
type_dict = {1:ANTIALIAS, 2:NEAREST, 3:BILINEAR, 4:BICUBIC}
type_correct = False
while not type_correct:
try:
new_height = int(input("请输入缩放后的图片高度:"))
new_weight = int(input("请输入缩放后的图片宽度:"))
print()
print("1.高质量(推荐) 2.低质量 3.双线性 4.三次样条插值")
resize_type = type_dict[int(input("请输入数字选择你想要的缩放算法:"))]
print()
print("1.在原文件目录输出(修改文件名) 2.在新文件夹resize_output输出(不改文件名)")
output_type = int(input("请输入数字选择你想要的输出方式:"))
# 如果选择在输出文件夹输出,那么创建输出文件夹
if output_type == 2:
if not exists(output_path):
mkdir(output_path)
type_correct = True
except:
print("输入值错误,请重新输入。\n")
print()
# 缩放图片
for img_path in img_paths:
try:
# 保存图片路径分割
dirname, filename = split(img_path)
fname, fename = splitext(filename)
if img_path.endswith(".gif") or img_path.endswith(".GIF"):
img = mimread(img_path)
for i in range(len(img)):
img[i] = fromarray(img[i]).resize((new_weight, new_height), resize_type)
if output_type == 1:
mimsave(dirname + "/" + "resize_" + fname + "_" + str(new_height) + "_" + str(new_weight) + fename, img, 'GIF')
elif output_type == 2:
mimsave(output_path + "/"+filename, img, 'GIF')
else:
img = open(img_path)
img = img.resize((new_weight, new_height), resize_type)
if output_type == 1:
img.save(dirname + "/" + "resize_" + fname + "_" + str(new_height) + "_" + str(new_weight) + fename)
elif output_type == 2:
img.save(output_path + "/"+filename)
except:
print("警告:你选择的文件"+img_path+"在运行时出现错误!")
print("所有正确图片已完成缩放,可以关闭窗口。")
sleep(60)