[Python] 纯文本查看 复制代码
# -*- coding: utf-8 -*-
import os
from PIL import Image
##################################################
folder = input("请拖拽入文件夹:")
cut_width = input("需要保留的宽度(像素):")
cut_height = input("需要保留的高度(像素):")
cut_list = ["整体缩放", "居中剪切", "左上角", "左下角", "右上角", "右下角"]
print("选择剪切基点:")
for i in range(len(cut_list)):
print(i + 1, ":", cut_list[i])
cut_value = input("裁剪基点:\n")
print("\n----------start----------\n")
print("操作文件夹:", folder, "\n剪切为:", cut_width, "x", cut_height, "(px)", "\n剪切模式为:", cut_list[int(cut_value) - 1], "\n")
def cut_picture(file_in, width, height, value):
img = Image.open(file_in)
_width, _height = img.size
if width > _width or height > _height:
print("超过图片大小限定!图片尺寸为:", _width, "x", _height, "不可剪至:", width, "x", height)
elif value == "1": # mediary
print("\n==> ", file_in, "=>缩放至:", width, "x", height, "已完成")
# don't cut picture, entire shrink to specify pixel of picture
image = Image.open(file_in)
resized_image = image.resize((width, height), Image.ANTIALIAS)
resized_image.save(file_in)
else:
print("==> ", file_in, "=>", width, "x", height, "已完成")
# 图像从左上角建立坐标系,四个值依次为距左的像素,距顶的像素,从左开始剪切到距离左多少的像素,从顶开始剪切到那里的像素。
# 即(左,上,右,底),构成一个矩形
crop = (0,0,0,0,)
if value == "3": # "leftTop"
crop = (0, 0, width, height)
elif value == "5": # "rightTop":
crop = (_width - width, 0, _width, height)
elif value == "6": # "bottomRight":
crop = (_width - width, _height - height, _width, _height)
elif value == "4": # "bottomLeft":
crop = (0, _height - height, width, _height)
elif value == "2": # "middle"
crop = (int((_width - width) / 2), int((_height - height) / 2), int((_width - width) / 2 + width),
int((_height - height) / 2 + height))
cropped = img.crop(crop) # (left, upper, right, lower)
cropped.save(file_in)
def find_folder(folder_path, width, height, cut_vaule):
folder_name = os.listdir(folder_path)
for v in range(len(folder_name)):
cut_picture(str(folder_path + folder_name[v]), width, height, cut_vaule) # (path,width,height,value)
input("\n\n进程结束.")
find_folder(folder + "\\", int(cut_width), int(cut_height), cut_value)