Image processing in Cloudflare Workers with WebAssembly

I was looking for an alternative to Sharp since it does not work on Cloudflare Workers as it uses Node.js APIs which are not yet supported by Cloudflare’s workerd runtime. Then I came across Photon, a high-performance Rust image processing library, which compiles to WebAssembly. Photon offers a variety of functions for resizing, transforming, watermarking, and more.

To use it on Cloudflare Workers, we can simply use @cf-wasm/photon.

Implementation

Create a Typescript Workers project and install the @cf-wasm/photon npm package.

npm create cloudflare@latest -- cf-workers-photon
cd cf-workers-photon
npm i @cf-wasm/photon

Now we shall modify the src/index.ts file.

import { PhotonImage, SamplingFilter, resize } from "@cf-wasm/photon";

export default {
  async fetch() {
    // url of image to fetch
    const imageUrl = "https://avatars.githubusercontent.com/u/314135";

    // fetch image and get the Uint8Array instance
    const inputBytes = await fetch(imageUrl)
      .then((res) => res.arrayBuffer())
      .then((buffer) => new Uint8Array(buffer));

    // create a PhotonImage instance
    const inputImage = PhotonImage.new_from_byteslice(inputBytes);

    // resize image using photon
    const outputImage = resize(
      inputImage,
      inputImage.get_width() * 0.5,
      inputImage.get_height() * 0.5,
      SamplingFilter.Nearest
    );

    // get webp bytes
    const outputBytes = outputImage.get_bytes_webp();

    // for other formats
    // png  : outputImage.get_bytes();
    // jpeg : outputImage.get_bytes_jpeg(quality);

    // call free() method to free memory
    inputImage.free();
    outputImage.free();

    // return the Response instance
    return new Response(outputBytes, {
      headers: {
        "Content-Type": "image/webp"
      }
    });
  }
} satisfies ExportedHandler;

The above code snippet fetches an image, creates a PhotonImage instance from image bytes and then resize it using resize function.

Run the following command to start the dev server: npm run dev.

To try it out, open the url: http://localhost:8787

This is a very simple example, there are many things you can do using the functions exported by photon. Try it out in your projects.

Share your love
Dev Kumar
Dev Kumar

Dev Kumar is a tech enthusiast and content creator specializing in coding tutorials and technical guides. As a key contributor to BytesAndBucks.com, he shares insights and hands-on tutorials aimed at helping users enhance their coding skills and navigate the tech landscape.

Articles: 4

Leave a Reply

Your email address will not be published. Required fields are marked *