@cf-wasm/photon

中文文档
0.4.0发布于 2026/08/01Apache-2.0TypeScriptES Module构建来源已验证近 30 天下载 63.4万

Photon library for Cloudflare workers, Next.js and Node.js.

原始使用文档
文档目录11 节
  1. Installation
  2. Usage
  3. Examples
  4. Cloudflare Workers
  5. Next.js (App Router)
  6. Next.js (Pages Router)
  7. Web Worker
  8. Documentation
  9. Reporting issues
  10. Awesome Projects
  11. Credits

@cf-wasm/photon

High-performance Rust image processing library (Photon) for Cloudflare workers, Next.js and Node.js.

Powered by @silvia-odwyer/photon
Built from commit 1390383
Synced with upstream on 2026-07-14 (IST).

Installation

npm install @cf-wasm/photon       # npm
yarn add @cf-wasm/photon          # yarn
pnpm add @cf-wasm/photon          # pnpm

Usage

Because package.json includes conditional exports for node, workerd, and edge-light, you can usually import directly from @cf-wasm/photon and let the runtime choose the correct entrypoint:

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

If you want to be explicit, import from a submodule instead:

  • Cloudflare Workers / Pages (Wrangler):

    import { PhotonImage } from "@cf-wasm/photon/workerd";
    
  • Next.js Edge Runtime:

    import { PhotonImage } from "@cf-wasm/photon/edge-light";
    
  • Node.js (inline):

    import { PhotonImage } from "@cf-wasm/photon/node";
    
  • Browser, Web Worker, etc. (experimental)

    import { PhotonImage } from "@cf-wasm/photon/others";
    

[!WARNING] Cloudflare Workers have strict memory caps (typically 128MB). To avoid exceeding those limits, validate input image size or reject oversized images before processing.

Examples

Here are some examples in which image is being resized and converted to webp format:

Cloudflare Workers

If you are using Cloudflare Workers, you can use it as shown below:

// src/index.ts
import { PhotonImage, SamplingFilter, resize } from "@cf-wasm/photon/workerd";

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

    // fetch image and get the bytes
    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 new Response(outputBytes, {
      headers: {
        "Content-Type": "image/webp",
      },
    });
  },
} satisfies ExportedHandler;

Next.js (App Router)

If you are using Next.js (App router) with edge runtime, you can use it as shown below:

// (src/)app/api/image/route.ts
import { type NextRequest } from "next/server";
import {
  PhotonImage,
  SamplingFilter,
  resize,
} from "@cf-wasm/photon/edge-light";

export const runtime = "edge";

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

  // fetch image and get the bytes
  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 new Response(outputBytes, {
    headers: {
      "Content-Type": "image/webp",
    },
  });
}

Next.js (Pages Router)

If you are using Next.js (Pages router) with edge runtime, you can use it as shown below:

// (src/)pages/api/image.ts
import { type NextRequest } from "next/server";
import {
  PhotonImage,
  SamplingFilter,
  resize,
} from "@cf-wasm/photon/edge-light";

export const config = {
  runtime: "edge",
  // see https://nextjs.org/docs/messages/edge-dynamic-code-evaluation
  unstable_allowDynamic: ["**/node_modules/@cf-wasm/**/*.js"],
};

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

  // fetch image and get the bytes
  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 new Response(outputBytes, {
    headers: {
      "Content-Type": "image/webp",
    },
  });
}

Web Worker

You can use others submodule and provide wasm binaries using initPhoton function to make it work on other runtime (i.e. Browser, Web Worker, etc).

[!WARNING] The others submodule is yet experimental. Breaking changes may be introduced without following semantic versioning.

@deox/worker-rpc can make messaging even more easier when using web workers.

Here is a working example for Web Workers when using Webpack bundler:

Create a worker.ts:

import {
  initPhoton,
  PhotonImage,
  SamplingFilter,
  resize,
} from "@cf-wasm/photon/others";
import { register, withOptions } from "@deox/worker-rpc/register";

const registered = register(async () => {
  // The wasm must be initialized first, you can provide photon wasm binaries from any source
  await initPhoton({
    module_or_path: new URL("@cf-wasm/photon/photon.wasm", import.meta.url),
  });

  return {
    resize: async (source: string, format?: "webp" | "png" | "jpeg") => {
      // fetch the source image and get bytes
      const imageBytes = new Uint8Array(
        await (await fetch(source)).arrayBuffer(),
      );

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

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

      let outputBytes: Uint8Array;

      switch (format) {
        case "png":
          // get png bytes
          outputBytes = outputImage.get_bytes();
          break;

        case "jpeg":
          // get jpeg bytes
          outputBytes = outputImage.get_bytes_jpeg(1);
          break;

        default:
          // get webp bytes
          outputBytes = outputImage.get_bytes_webp();
      }

      // Explicitly free rust memory
      outputImage.free();
      inputImage.free();

      // transfer bytes to main thread
      return withOptions(outputBytes, [outputBytes.buffer]);
    },
  };
});

export type Registered = typeof registered;

Now you can use it in your entrypoints:

import { Worker } from "@deox/worker-rpc";
import type { Registered } from "./worker";

const worker = new Worker<Registered>(
  new URL("./worker", import.meta.url),
  undefined,
);

const element = document.getElementById("demo_image") as HTMLImageElement;

worker.proxy
  .resize("https://avatars.githubusercontent.com/u/100576030")
  .then((bytes) => {
    const url = URL.createObjectURL(new Blob([bytes]));

    element.src = url;
  });

Documentation

To explore all the functions, visit the official documentation.

Reporting issues

This library is a fork of silvia-odwyer/photon, so consider opening issues or feature requests there.

For WebAssembly-related issues, you can open an issue in this repository.

Awesome Projects

Following is a list of projects built using this library:

Credits

All credit goes to @silvia-odwyer/photon.

版本与发布记录

@cf-wasm/photon 共发布 42 个版本,首次发布于 2023/11/22;过去 12 个月发布了 8 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.4.0latest2026/08/013 个月前
0.3.72026/07/143 个月前
0.3.62026/05/305 个月前
0.3.52026/05/046 个月前
0.3.42025/12/0411 个月前
0.3.12025/11/2611 个月前

关于 @cf-wasm/photon 的常见问题

@cf-wasm/photon 是什么?

Photon library for Cloudflare workers, Next.js and Node.js.

如何安装 @cf-wasm/photon?

在项目目录运行 npm install @cf-wasm/photon,或使用 pnpm add / yarn add / bun add。

@cf-wasm/photon 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@cf-wasm/photon 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@cf-wasm/photon 可以商用吗?

@cf-wasm/photon 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@cf-wasm/photon 的下载量有多少?

根据 npm 官方下载统计,@cf-wasm/photon 在 2026/10/10 – 2026/11/08 这 30 天内被下载 634,415 次,日均约 21,147 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@cf-wasm/photon 还在维护吗?

最新版本 0.4.0 发布于 2026/08/01(3 个月前);至今共发布 42 个版本,其中过去 12 个月发布了 8 个;首次发布于 2023/11/22。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。