resize-img-api/index.ts

169 lines
5.4 KiB
TypeScript

import { Hono } from "hono";
import { cors } from "hono/cors";
import { etag } from "hono/etag";
import { logger } from "hono/logger";
import { prettyJSON } from "hono/pretty-json";
import { html } from "hono/html";
import sharp from "sharp";
const homepage = html`
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
<meta charSet="utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="og:type" content="website" />
<title>Resize Images API</title>
<meta name="description" content="Resize images via API">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css" />
</head>
<body>
<main class="container">
<h1>Resize images API</h1>
<nav style="justify-content: center; max-width: 800px; margin-left: auto; margin-right: auto;">
<a href="#try-now">Try now</a>
<span style="margin-left: 1rem; margin-right: 1rem;"> | </span>
<a href="#docs">Docs</a>
</nav>
<style>
h1 {
margin-top: 2rem;
margin-bottom: 1rem;
text-align: center;
}
h1 + nav {
margin-bottom: 3rem;
}
</style>
<article style="max-width: 800px; margin-left: auto; margin-right: auto; padding: 3rem 2rem;">
<h2 id="try-now">Try now</h2>
<form action="/api/preview" method="post" target="_blank">
<fieldset>
<label>
URL
<input
type="url"
name="url"
placeholder="https://example.com"
required
/>
</label>
<label>
Width
<input
type="number"
name="width"
placeholder="200"
min="1"
max="2000"
steps="1"
/>
</label>
<label>
Height
<input
type="number"
name="height"
placeholder="200"
min="1"
max="2000"
steps="1"
/>
</label>
</fieldset>
<button type="submit">Resize</button>
</form>
</article>
<article style="max-width: 800px; margin-left: auto; margin-right: auto; padding: 3rem 2rem;">
<h2 id="docs">Docs</h2>
<p>The structure of the API path is:</p>
<p><pre>/api/imgresize/:width/:height/:url</pre></p>
<p>Where <code>width</code> and <code>height</code> can be numbers in pixels or <code>auto</code>.</p>
<p>The URL should be URL encoded, which can be done in JS with <code>encodeURIComponent</code>. See <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent" target="_blank" rel="noopener noreferrer">MDN ref</a>.</p>
<p>Example for <a href="https://memori.ai/logo.png" target="_blank" rel="noopener noreferrer">https://memori.ai/logo.png</a>:</p>
<p><pre>https%3A%2F%2Fmemori.ai%2Flogo.png</pre></p>
<p>Then call the API as, for example:</p>
<p><pre>/api/imgresize/200/200/https%3A%2F%2Fmemori.ai%2Flogo.png</pre></p>
<p>You can also specify a format using the querystring <code>?format=</code> and indicating one of the following: avif, gif, heif, jpeg, jpg, jp2, pdf, png, svg, tiff, webp. Note: Experimental!</p>
</article>
</main>
</body>
</html>
`;
const app = new Hono();
app.use(prettyJSON());
app.use(etag(), logger());
app.use("/api/*", cors());
app.get("/", (c) => {
return c.html(homepage);
});
app.post("/api/preview", async (c) => {
const body = await c.req.parseBody();
c.header("Cache-Control", "s-maxage=31536000, stale-while-revalidate");
const url = body["url"];
if (!url || typeof url !== "string") {
c.status(400);
return c.json({ error: "No URL provided" });
}
const width = body["width"];
const height = body["height"];
const w = width && width !== "auto" ? Number(width) : 200;
const h = height && height !== "auto" ? Number(height) : 200;
return c.redirect(`/api/imgresize/${w}/${h}/${encodeURIComponent(url)}`);
});
app.get("/api/imgresize/:width/:height/:url", async (c) => {
const { width, height, url } = c.req.param();
const format = c.req.query("format");
c.header("Cache-Control", "s-maxage=31536000, stale-while-revalidate");
c.header("Content-Type", `image/jpeg`);
const decodedUrl = decodeURIComponent(url as string);
const readStream = await fetch(decodedUrl, { cache: "no-cache" });
const input = Buffer.from(await readStream.arrayBuffer());
const w = width && width !== "auto" ? Number(width) : undefined;
const h = height && height !== "auto" ? Number(height) : undefined;
const outputBuffer = await sharp(input)
// outputBuffer contains JPEG image data
// no wider and no higher than w and h pixels
// and no larger than the input image
.resize({
width: w,
height: h,
fit: sharp.fit.inside,
withoutEnlargement: true,
})
.toFormat(
format && sharp.format[format as keyof typeof sharp.format] !== undefined
? sharp.format[format as keyof typeof sharp.format]
: sharp.format.jpeg
)
.toBuffer();
c.status(200);
return c.body(outputBuffer);
});
export default {
port: Bun.env.PORT || 8787,
fetch: app.fetch,
};