This commit is contained in:
doudou201703
2026-09-19 16:13:13 +08:00
parent 922583becb
commit 734dc4f46a
2 changed files with 41 additions and 2 deletions
@@ -0,0 +1,41 @@
import os
import django
from django_six_demo.settings import base_dir_name
os.environ.setdefault(key="DJANGO_SETTINGS_MODULE", value=f"{base_dir_name}.settings")
django.setup()
from pydantic import BaseModel, Field
from pathlib import Path
import base64
from PIL import Image
from typing import Union
class ImageToDataURI(BaseModel):
"""图片转 Data URI 工具类"""
data_uri: str = Field(description="Data URI 格式的图片数据")
@classmethod
def from_path(cls, file_path: Union[str, Path]) -> "ImageToDataURI":
"""从文件路径转换"""
path = Path(file_path)
if not path.exists():
raise FileNotFoundError(f"文件不存在: {path}")
# 读取原始字节
file_bytes = path.read_bytes()
# 获取 MIME 类型
img = Image.open(path)
mime_type = img.get_format_mimetype() or "image/png"
print(mime_type)
# 转 Base64 并拼接 Data URI
base64_str = base64.b64encode(file_bytes).decode("utf-8")
data_uri = f"data:{mime_type};base64,{base64_str}"
return data_uri
if __name__ == "__main__":
pass