|
from fastapi import APIRouter, Query, HTTPException |
|
from fastapi.responses import StreamingResponse |
|
from PIL import Image |
|
import requests |
|
from io import BytesIO |
|
import base64 |
|
|
|
router = APIRouter() |
|
|
|
def image_to_custom_string(img: Image.Image) -> str: |
|
img = img.convert("RGB").resize((32, 32)) |
|
pixels = list(img.getdata()) |
|
|
|
|
|
pixel_data = ";".join([f"{r},{g},{b}" for r, g, b in pixels]) |
|
return pixel_data |
|
|
|
def custom_string_to_image(data: str, size=(32, 32)) -> Image.Image: |
|
pixels = [ |
|
tuple(map(int, pixel.split(","))) |
|
for pixel in data.strip().split(";") if pixel |
|
] |
|
img = Image.new("RGB", size) |
|
img.putdata(pixels) |
|
return img |
|
|
|
@router.get("/encode") |
|
def encode_image(url: str = Query(..., description="URL da imagem")): |
|
try: |
|
response = requests.get(url) |
|
image = Image.open(BytesIO(response.content)) |
|
encoded_string = image_to_custom_string(image) |
|
return {"encoded": encoded_string} |
|
except Exception as e: |
|
raise HTTPException(status_code=400, detail=f"Erro ao processar imagem: {e}") |
|
|
|
@router.get("/decode") |
|
def decode_image(encoded: str = Query(..., description="String da imagem codificada")): |
|
try: |
|
image = custom_string_to_image(encoded) |
|
buffer = BytesIO() |
|
image.save(buffer, format="PNG") |
|
buffer.seek(0) |
|
return StreamingResponse(buffer, media_type="image/png") |
|
except Exception as e: |
|
raise HTTPException(status_code=400, detail=f"Erro ao decodificar imagem: {e}") |