This commit is contained in:
2024-11-04 05:20:42 +08:00
parent e990473dcd
commit 07de4d5fd5
24 changed files with 1385 additions and 2 deletions

41
download.py Normal file
View File

@@ -0,0 +1,41 @@
import io
import os
import requests
from PIL import Image, ImageFile
from models.oss import bucket_image2, bucket_webp
from configs.config import IMAGES_PATH
ImageFile.LOAD_TRUNCATED_IMAGES = True
# 下载图片(使用OSS下载)
def download_image(url:str) -> Image:
if url.startswith('http://image.gameuiux.cn/') or url.startswith('https://image.gameuiux.cn/'):
try:
url = url.replace('http://image.gameuiux.cn/', '').replace('https://image.gameuiux.cn/', '')
obj = bucket_image2.get_object(url).read()
return Image.open(io.BytesIO(obj))
except Exception:
return None
else:
try:
response = requests.get(url)
return Image.open(io.BytesIO(response.content))
except Exception:
print('图片下载失败:', url)
return None
# 生成缩略图, 写入OSS
def generate_thumbnail(image:Image, id:int, version:str, n:int, w:int, ext:str):
path = f"{id}-{version}@{n}x{w}.{ext}"
if bucket_webp.object_exists(path):
print('缩略图已经存在:', path)
return
# 将 image 对象复制一份, 防止影响原图
image = image.copy()
image.thumbnail((n*w, image.size[1]))
image.save(f"{IMAGES_PATH}/{path}", ext, save_all=True)
bucket_webp.put_object_from_file(path, f"{IMAGES_PATH}/{path}")
os.remove(f"{IMAGES_PATH}/{path}")
print('缩略图写入 OSS:', path)