create an express server for resizing images with sharp, should take source image, w, h, and quality as params in typescript

Here's an example of how to create an Express server in TypeScript that uses the Sharp module to resize images. The request URL should include the source image's path, width, height, and quality options as query parameters:

index.ts
import express from "express";
import sharp from "sharp";

const app = express();

app.get("/resize", async (req, res) => {
  try {
    const { src, w, h, q } = req.query;
    const width = parseInt(w as string);
    const height = parseInt(h as string);
    const quality = parseInt(q as string);
    const image = await sharp(src as string).resize(width, height).jpeg({ quality }).toBuffer();
    res.set("Content-Type", "image/jpeg");
    res.send(image);
  } catch (error) {
    console.error(error);
    res.status(500).send("Internal server error");
  }
});

app.listen(3000, () => {
  console.log("Server listening on port 3000");
});
642 chars
24 lines

Here's an example request:

index.ts
GET http://localhost:3000/resize?src=my-image.jpg&w=200&h=200&q=80
67 chars
2 lines

This will resize the image located at my-image.jpg to have a width and height of 200 pixels, and a quality of 80. The server will return the resized image as a JPEG.

related categories

gistlibby LogSnag