当前位置:   article > 正文

fastapi接收图片文件_fastapi 接收图片

fastapi 接收图片
#api接口,主函数
import base64
import io
import cv2
import os
import time
from PIL import Image
import numpy as np
from fastapi import FastAPI,HTTPException
import uvicorn

app = FastAPI()

#############################################
# @app.post("/uploadfile/")
# async def create_upload_file(file: UploadFile = File(...)):
#     contents = await file.read()
#     return {"filename": file.filename, "contents": contents}

@app.post("/upload_image")
async def upload_image(file: UploadFile):
    if not file:
        raise HTTPException(status_code=400, detail="没有收到图片文件")   
    image = await file.read() 
    try:
        # 将图片转换为base64编码
        image_base64 = base64.b64encode(image).decode('utf-8')
        
        # 将base64编码的图片解码为原始图像
        image_array = np.frombuffer(base64.b64decode(image_base64), dtype=np.uint8)
        image = cv2.imdecode(image_array, cv2.IMREAD_COLOR)
        
        # 保存图像到临时文件
        cv2.imwrite("temp.jpg", image)
        img_path = "temp.jpg"
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
    
    return {"image_path": img_path}
@app.get("/")
async def read_root():
    return {"Hello": "World"}

if __name__ == '__main__':
    uvicorn.run(app, host="192.168.0.1", port=int("8000"))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/916792
推荐阅读
相关标签
  

闽ICP备14008679号