iTranslated by AI
Compressing Images on Cloudflare Workers Free Plan
Compressing Images on Cloudflare Workers' Free Plan
When deploying a Next.js project to Cloudflare, the challenge is the automatic image compression feature provided by Vercel. While Cloudflare Workers seems like a candidate to achieve this on Cloudflare, the free plan does not provide image compression features. Driven by a determination to keep things free at any cost, I decided to write my own image conversion code.
How to Convert Images
On Cloudflare Workers, the CPU time that can be processed in a single request is 10ms. This is pure processing time, as it does not include the wait time for asynchronous access. Native code would be the best for high-speed processing, but of course, it cannot be used. Therefore, I decided to use WebAssembly. While Rust is currently the mainstream for WebAssembly, I chose C++ this time because I wanted to use libwebp directly.
Using Emscripten's emcc as the Compiler
Emscripten is a tool that can compile C++ into JavaScript + WebAssembly. By using this, you can compile code written in C++ into WebAssembly and call it from JavaScript. So, I set out to create it immediately.
libpng and libjpeg are readily available in Emscripten
Emscripten provides a mechanism called "ports" for incorporating existing libraries. By using this mechanism, you can build with libpng or libjpeg included simply by specifying options at compile time. However, libwebp is not automatically included. You need to download the source yourself and include it in the build.
SDL2 is also included in Emscripten
SDL2 is a library that allows you to easily load and draw images. This is also included in the ports. If you make libpng, libjpeg, and libwebp available, you can load images simply by passing the binary to SDL. However, WebP output is not supported, so you will need to use libwebp's commands directly for that part.
Image Conversion Code
So, I created it. It's remarkably simple to write, yet for some reason, I couldn't find this kind of code online.
#include <emscripten.h>
#include <emscripten/bind.h>
#include <emscripten/val.h>
#include <webp/encode.h>
#include <SDL_image.h>
#include <SDL2/SDL.h>
using namespace emscripten;
val optimize(std::string img_in, float width, float height, float quality) {
SDL_RWops* rw = SDL_RWFromConstMem(img_in.c_str(), img_in.size());
if (!rw) {
return val::null();
}
SDL_Surface* srcSurface = IMG_Load_RW(rw, 1);
SDL_FreeRW(rw);
if (!srcSurface) {
return val::null();
}
int srcWidth = srcSurface->w;
int srcHeight = srcSurface->h;
if (srcWidth == 0 || srcHeight == 0) {
SDL_FreeSurface(srcSurface);
return val::null();
}
int outWidth = width?width:srcWidth;
int outHeight = height?height:srcHeight;
float aspectSrc = static_cast<float>(srcWidth) / srcHeight;
float aspectDest = outWidth / outHeight;
if (aspectSrc > aspectDest) {
outHeight = outWidth / aspectSrc;
} else {
outWidth = outHeight * aspectSrc;
}
SDL_Surface* newSurface = SDL_CreateRGBSurfaceWithFormat(0, static_cast<int>(outWidth), static_cast<int>(outHeight), 32, SDL_PIXELFORMAT_RGBA32);
if (!newSurface) {
SDL_FreeSurface(srcSurface);
return val::null();
}
SDL_BlitScaled(srcSurface, nullptr, newSurface, nullptr);
SDL_FreeSurface(srcSurface);
uint8_t* img_out = nullptr;
int stride = static_cast<int>(outWidth) * 4;
size_t size = WebPEncodeRGBA(reinterpret_cast<uint8_t*>(newSurface->pixels), static_cast<int>(outWidth), static_cast<int>(outHeight), stride, quality, &img_out);
if (size == 0 || !img_out) {
SDL_FreeSurface(newSurface);
return val::null();
}
val result = val::global("Uint8Array").new_(typed_memory_view(size, img_out));
WebPFree(img_out);
SDL_FreeSurface(newSurface);
return result;
}
EMSCRIPTEN_BINDINGS(my_module) {
function("optimize", &optimize);
}
Creating a package that works on Cloudflare Workers
To call WebAssembly from JavaScript in Cloudflare Workers, you need to import the wasm. Unlike general V8 engines, you cannot download wasm over the network. Therefore, you must create a package that includes the wasm.
By the way, Cloudflare Workers limits the package size per Worker to 1MB. Although the wasm size was over 1MB, it was around 400KB when compressed as a package, so it was safe.
I also tried implementing libavif encoding, but I gave up on it because the package size exceeded 1MB even after compression.
Running on Cloudflare Workers
Using the wasm-image-optimization package mentioned above, I created a Worker that is compatible with Next.js's image compression parameters. With this, you can utilize Next.js image compression parameters as-is.
import { optimizeImage } from "wasm-image-optimization";
export interface Env {}
const isValidUrl = (url: string) => {
try {
new URL(url);
return true;
} catch (err) {
return false;
}
};
const handleRequest = async (
request: Request,
_env: Env,
ctx: ExecutionContext
): Promise<Response> => {
const url = new URL(request.url);
const params = url.searchParams;
const imageUrl = params.get("url");
if (!imageUrl || !isValidUrl(imageUrl)) {
return new Response("url is required", { status: 400 });
}
const cache = caches.default;
const cachedResponse = await cache.match(
new Request(url.toString(), request)
);
if (cachedResponse) {
return cachedResponse;
}
const width = params.get("w");
const quality = params.get("q");
const srcImage = await fetch(imageUrl, { cf: { cacheKey: imageUrl } })
.then((res) => (res.ok ? res.arrayBuffer() : null))
.catch((e) => null);
if (!srcImage) {
return new Response("image not found", { status: 404 });
}
const image = await optimizeImage({
image: srcImage,
width: width ? parseInt(width) : undefined,
quality: quality ? parseInt(quality) : undefined,
});
const response = new Response(image, {
headers: {
"Content-Type": "image/webp",
"Cache-Control": "public, max-age=31536000, immutable",
},
});
ctx.waitUntil(cache.put(request, response.clone()));
return response;
};
export default {
fetch: handleRequest,
};
By specifying the Worker's deployment address in next.config.js as shown below, you can compress images through the Worker.
/**
* @type { import("next").NextConfig}
*/
const config = {
images: {
path: "https://xxx.yyy.workers.dev/",
},
};
export default config;
Testing the Conversion
Let's try converting a 1024*1024, 266KB image using the options ?url=https://xxx&w=256&q=75.

It turned into a 256*256 image. The size is 18.4KB.

Summary
Cloudflare Workers can be used for free up to 100,000 requests per day, even on the free plan. This should be more than enough for users who want to stick to free services. If it doesn't exist, build it—that's the secret to getting by for free.
Discussion