上传图片,返回mediaId Args: at: Access Token image_bytes: 图片字节数据 aspect_ratio: 图片或视频宽高比(会自动转换为图片格式) project_id: 项目ID(新上传接口可使用) Returns: mediaId
(
self,
at: str,
image_bytes: bytes,
aspect_ratio: str = "IMAGE_ASPECT_RATIO_LANDSCAPE",
project_id: Optional[str] = None
)
| 1419 | return output.getvalue() |
| 1420 | |
| 1421 | async def upload_image( |
| 1422 | self, |
| 1423 | at: str, |
| 1424 | image_bytes: bytes, |
| 1425 | aspect_ratio: str = "IMAGE_ASPECT_RATIO_LANDSCAPE", |
| 1426 | project_id: Optional[str] = None |
| 1427 | ) -> str: |
| 1428 | """上传图片,返回mediaId |
| 1429 | |
| 1430 | Args: |
| 1431 | at: Access Token |
| 1432 | image_bytes: 图片字节数据 |
| 1433 | aspect_ratio: 图片或视频宽高比(会自动转换为图片格式) |
| 1434 | project_id: 项目ID(新上传接口可使用) |
| 1435 | |
| 1436 | Returns: |
| 1437 | mediaId |
| 1438 | """ |
| 1439 | # 转换视频aspect_ratio为图片aspect_ratio |
| 1440 | # VIDEO_ASPECT_RATIO_LANDSCAPE -> IMAGE_ASPECT_RATIO_LANDSCAPE |
| 1441 | # VIDEO_ASPECT_RATIO_PORTRAIT -> IMAGE_ASPECT_RATIO_PORTRAIT |
| 1442 | if aspect_ratio.startswith("VIDEO_"): |
| 1443 | aspect_ratio = aspect_ratio.replace("VIDEO_", "IMAGE_") |
| 1444 | |
| 1445 | # 自动检测图片 MIME 类型 |
| 1446 | mime_type = self._detect_image_mime_type(image_bytes) |
| 1447 | |
| 1448 | # 编码为base64 (去掉前缀) |
| 1449 | image_base64 = base64.b64encode(image_bytes).decode('utf-8') |
| 1450 | |
| 1451 | # 优先尝试新版上传接口: /v1/flow/uploadImage |
| 1452 | # 若失败则自动回退到旧接口,保证兼容 |
| 1453 | ext = "png" if "png" in mime_type else "jpg" |
| 1454 | upload_file_name = f"flow2api_upload_{int(time.time() * 1000)}.{ext}" |
| 1455 | new_url = f"{self.api_base_url}/flow/uploadImage" |
| 1456 | normalized_project_id = str(project_id or "").strip() |
| 1457 | new_client_context = { |
| 1458 | "sessionId": self._generate_session_id(), |
| 1459 | "tool": "PINHOLE" |
| 1460 | } |
| 1461 | if normalized_project_id: |
| 1462 | new_client_context["projectId"] = normalized_project_id |
| 1463 | |
| 1464 | new_json_data = { |
| 1465 | "clientContext": new_client_context, |
| 1466 | "fileName": upload_file_name, |
| 1467 | "imageBytes": image_base64, |
| 1468 | "isHidden": False, |
| 1469 | "isUserUploaded": True, |
| 1470 | "mimeType": mime_type |
| 1471 | } |
| 1472 | |
| 1473 | # 兼容回退:旧接口 :uploadUserImage |
| 1474 | legacy_url = f"{self.api_base_url}:uploadUserImage" |
| 1475 | legacy_json_data = { |
| 1476 | "imageInput": { |
| 1477 | "rawImageBytes": image_base64, |
| 1478 | "mimeType": mime_type, |