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"))
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值