save
This commit is contained in:
+34
-6
@@ -11,12 +11,18 @@ import base64
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
# 添加父目录到路径以导入config
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
import config
|
||||
|
||||
import httpx
|
||||
from PIL import Image
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import FileResponse
|
||||
@@ -208,12 +214,34 @@ async def try_on(req: TryOnRequest):
|
||||
async with httpx.AsyncClient(timeout=30.0) as dl_client:
|
||||
result_bytes = await fetch_image_bytes(dl_client, filename, subfolder, type_)
|
||||
|
||||
# 将图片保存到临时文件,上传到 OSS
|
||||
suffix = Path(filename).suffix or ".png"
|
||||
object_name = f"tryon/{uuid.uuid4().hex}{suffix}"
|
||||
with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
|
||||
tmp.write(result_bytes)
|
||||
tmp_path = tmp.name
|
||||
# 根据配置转换图片格式并上传到 OSS
|
||||
output_format = config.OUTPUT_FORMAT.lower()
|
||||
file_ext = '.jpg' if output_format == 'jpg' else '.png'
|
||||
object_name = f"tryon/{uuid.uuid4().hex}{file_ext}"
|
||||
|
||||
# 使用PIL处理图片
|
||||
img = Image.open(io.BytesIO(result_bytes))
|
||||
|
||||
if output_format == 'jpg':
|
||||
# JPG格式:转换为RGB模式
|
||||
if img.mode in ('RGBA', 'LA', 'P'):
|
||||
rgb_img = Image.new('RGB', img.size, (255, 255, 255))
|
||||
if img.mode == 'P':
|
||||
img = img.convert('RGBA')
|
||||
rgb_img.paste(img, mask=img.split()[-1] if img.mode in ('RGBA', 'LA') else None)
|
||||
img = rgb_img
|
||||
elif img.mode != 'RGB':
|
||||
img = img.convert('RGB')
|
||||
|
||||
# 保存为JPG
|
||||
with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as tmp:
|
||||
img.save(tmp, format='JPEG', quality=config.JPG_QUALITY)
|
||||
tmp_path = tmp.name
|
||||
else:
|
||||
# PNG格式:保持原样
|
||||
with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as tmp:
|
||||
img.save(tmp, format='PNG')
|
||||
tmp_path = tmp.name
|
||||
|
||||
try:
|
||||
result_url = upload_to_oss(tmp_path, object_name)
|
||||
|
||||
Reference in New Issue
Block a user