通过等比例缩放图片后在多出的部分添入黑色来实现等比例调整图片大小
等比例缩放
img_width = self.img.size[0] img_height = self.img.size[1] if img_width > img_height: rate = self.aspect_width / img_width else: rate = self.aspect_height / img_height rate = round(rate, 1) self.img = self.img.resize((int(img_width * rate), int(img_height * rate)))添入黑色
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)))保存图片
self.result_image.save(os.path.join('保存路径', os.path.basename(file_name)))代码连接
https://github.com/guo-mingyu/Batch-output-pictures-/
代码可以直接使用