支持JPEG照片并保留原始尺寸

This commit is contained in:
2026-11-19 14:45:26 +08:00
parent 7520949b3b
commit 08f18b784f
5 changed files with 25 additions and 10 deletions
+7 -6
View File
@@ -14,6 +14,7 @@ from typing import Literal
from fastapi import Depends, HTTPException, Query, Request
from fastapi.responses import FileResponse
from PIL.Image import DecompressionBombError
from pydantic import BaseModel, Field, field_validator
from sqlalchemy import select, insert, update, delete, func, text, or_
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
@@ -224,13 +225,12 @@ async def material_photos(db, material_id, owner_id):
def convert_photo(raw):
from PIL import Image, ImageOps
with warnings.catch_warnings():
warnings.simplefilter('error', Image.DecompressionBombWarning)
warnings.simplefilter('error', Image.DecompressionBombError)
with Image.open(io.BytesIO(raw)) as image:
if image.format not in ('JPEG', 'PNG', 'WEBP') or image.width * image.height > 24000000:
raise ValueError('仅支持24百万像素以内的JPG、PNG、WebP照片')
if image.format not in ('JPEG', 'PNG', 'WEBP'):
raise ValueError('仅支持JPG、PNG、WebP照片')
image = ImageOps.exif_transpose(image).convert('RGB')
image.thumbnail((2400, 2400))
output = io.BytesIO(); image.save(output, 'JPEG', quality=85)
output = io.BytesIO(); image.save(output, 'JPEG', quality=90)
return output.getvalue()
@@ -303,7 +303,8 @@ def install(app, get_db, current_user, photo_root, visible_clause):
count = (await db.execute(select(func.count()).select_from(center_photos).where(center_photos.c.owner_id == viewer['id'], center_photos.c.created_at > now_ms() - 86400000))).scalar()
if count >= DAILY_PHOTO_LIMIT: raise HTTPException(429, f'今日照片上传已达{DAILY_PHOTO_LIMIT}张')
try: data = await asyncio.to_thread(convert_photo, bytes(raw))
except Exception as exc: raise HTTPException(422, '照片无效,仅支持JPG、PNG、WebP,最大24百万像素') from exc
except DecompressionBombError as exc: raise HTTPException(422, '图片数据过大,无法安全处理') from exc
except Exception as exc: raise HTTPException(422, '照片无效,仅支持JPG、PNG、WebP') from exc
key = uuid.uuid4().hex
folder = photo_root(); folder.mkdir(parents=True, exist_ok=True)
path = folder / (key + '.jpg')