File size: 1,014 Bytes
4b2ecc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, HTTPException
import httpx
from rembg import remove
from io import BytesIO
from fastapi.responses import StreamingResponse

app = FastAPI()

@app.get("/remove-background/")
async def remove_background(image_url: str):
    try:
        # Baixa a imagem da URL fornecida
        async with httpx.AsyncClient() as client:
            response = await client.get(image_url)
            response.raise_for_status()  # Verifica se a URL foi bem-sucedida
            image_data = response.content
        
        # Remover o fundo da imagem usando o rembg
        output_image = remove(image_data)

        # Retorna a imagem com o fundo removido como resposta
        return StreamingResponse(BytesIO(output_image), media_type="image/png")
    
    except httpx.RequestError as e:
        raise HTTPException(status_code=400, detail="Erro ao baixar a imagem: " + str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail="Erro ao processar a imagem: " + str(e))