from tkinter import * #导入tkinter from tkinter import messagebox #引入弹出框 #from typing import Any, Union import pymysql #导入pymysql from pymysql.cursors import Cursor #导入游标 from hashlib import sha1 #导入hashlib,引用函数 import tkinter as tk from PIL import Image #图像缩放 from tkinter import Scrollbar from tkinter import ttk # 导入内部包 from tkinter.ttk import Treeview class image_aspect(): #图像转换 def __init__(self, image_file, aspect_width, aspect_height): self.img = Image.open(image_file) self.aspect_width = aspect_width self.aspect_height = aspect_height self.result_image = None def change_aspect_rate(self): img_width = self.img.size[0] img_height = self.img.size[1] if (img_width / img_height) > (self.aspect_width / self.aspect_height): rate = self.aspect_width / img_width else: rate = self.aspect_height / img_height rate = round(rate, 1) print(rate) self.img = self.img.resize((int(img_width * rate), int(img_height * rate))) return self def past_background(self): self.result_image = Image.new("RGB", [self.aspect_width, self.aspect_height], (0, 0, 0, 255)) self.result_image.paste(self.img, ( int((self.aspect_width - self.img.size[0]) / 2), int((self.aspect_height - self.img.size[1]) / 2))) return self def save_result(self, file_name): self.result_image.save(file_name) if __name__ == "__main__": #输出图像 image_aspect("1.gif", 150, 250).change_aspect_rate().past_background().save_result( "515.gif")