46 lines
1.2 KiB
Python
46 lines
1.2 KiB
Python
import os
|
||
from fastapi import UploadFile
|
||
from PIL import Image
|
||
|
||
|
||
def create_folder(*path):
|
||
"""根据路径创建文件夹"""
|
||
folder_path = os.path.join(*path)
|
||
try:
|
||
os.makedirs(folder_path, exist_ok=True)
|
||
except Exception as e:
|
||
print(f"创建文件夹时错误: {e}")
|
||
|
||
|
||
def save_images(*path, file: UploadFile):
|
||
"""
|
||
保存上传的图片
|
||
:param path: 路径
|
||
:param file: 文件
|
||
:return:
|
||
"""
|
||
save_path = os.path.join(*path, file.filename)
|
||
|
||
os.makedirs(os.path.dirname(save_path), exist_ok=True)
|
||
with open(save_path, "wb") as f:
|
||
for line in file.file:
|
||
f.write(line)
|
||
return save_path
|
||
|
||
|
||
def create_thumbnail(input_image_path, out_image_path, size=(116, 70)):
|
||
"""
|
||
给图片生成缩略图
|
||
:param input_image_path:
|
||
:param out_image_path:
|
||
:param size: 缩略的尺寸
|
||
:return:
|
||
"""
|
||
with Image.open(input_image_path) as image:
|
||
# 使用thumbnail方法生成缩略图,参数size指定缩略图的最大尺寸
|
||
# 注意:thumbnail方法会保持图片的宽高比不变
|
||
image.thumbnail(size)
|
||
os.makedirs(os.path.dirname(out_image_path), exist_ok=True)
|
||
# 保存生成的缩略图
|
||
image.save(out_image_path, 'JPEG')
|