图片批量缩放工具

图片批量缩放工具


使用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)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值