Rescaling an image using the Nearest Neighbor algorithm with Python and Pillow.

Tiempo de lectura: < 1 minuto

Hoy you are sharing a small function that allows image scaling using nearest neighbor and directly from the server.

Cuenca agua - pexels

You will reduce the computational cost of the front to scale images.

I recommend using it for pixel art style. Although it may work with other images or you’ll need to change the resizing algorithm.

First, we install pillow:

pip install pillow

And now, we create an endpoint that handles returning the resized image:

from fastapi import Query from PIL import Image from io import BytesIO from fastapi.responses import Response @user.get("/image/{nombre_imagen:path}", status_code=status.HTTP_200_OK) def get_imagen_accesorios(nombre_imagen: str, w: int = Query(None), h: int = Query(None)): imagen_folder = "images/public" imagen_png = os.path.join(imagen_folder, nombre_imagen + ".png") imagen_jpg = os.path.join(imagen_folder, nombre_imagen + ".jpg") if os.path.isfile(imagen_png): imagen_path = imagen_png media_type = "image/png" elif os.path.isfile(imagen_jpg): imagen_path = imagen_jpg media_type = "image/jpeg" else: raise HTTPException(status_code=404, detail="Error, no existe la imagen.") img = Image.open(imagen_path) # Si se solicitan dimensiones, aplicar escalado nearest neighbor if w and h: img = img.resize((w, h), Image.NEAREST) buf = BytesIO() img.save(buf, format="PNG") buf.seek(0) return Response(content=buf.getvalue(), media_type=media_type, headers={ "Cache-Control": "public, max-age=31536000" }) 

You need to save your images in .jpg or .png format in the images/public directory.

GET /image-accesorios/cortina?w=256&h=256

Leave a Comment