# @cf-wasm/photon 中文文档

规范地址：https://npmcn.com/package/%40cf-wasm/photon/

版本：0\.4\.0
npm 元数据更新时间：2026-08-01T02:29:47.861Z
中文译文更新时间：2026-11-09T08:29:47.573Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40cf-wasm/photon
原文对照：https://npmcn.com/package/%40cf-wasm/photon/?lang=original
项目主页：https://github.com/fineshopdesign/cf-wasm/tree/main/packages/photon#readme
源码仓库：https://github.com/fineshopdesign/cf-wasm

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：6.3 MB，26 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：1 个
- 首次发布：2023-11-22T10:00:55.574Z
- 最新版本发布：2026-08-01T02:29:47.485Z
- 近 30 天下载量：634415（2026-10-10 至 2026-11-08，npm 官方下载统计）
- 已发布版本数：42（近 12 个月 8 个）

## 中文简介

为Cloudflare工作的光子图书馆,Next.js和Node.js.

## 安装

```sh
npm install @cf-wasm/photon
```

也可以使用：`pnpm add @cf-wasm/photon`、`yarn add @cf-wasm/photon`、`bun add @cf-wasm/photon`

## README

# @ cf-wasm/ 图片

为Cloudflare工人,Next.js和Node.js的高性能 Rust图像处理库(Photon).

电源 [@silvia-odwyer/图片](https://github.com/silvia-odwyer/photon)  
由犯罪建造 [`1390383`](https://github.com/silvia-odwyer/photon/tree/139038385b0cca7a743a2e5dd451c9e626b6b880)  
与上游同步于 `2026-07-14 (IST)`。 。 。 .

## 安装

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

## 使用量

因为 `package.json` 包括: `node`, (中文(简体) ), `workerd`,以及 `edge-light`,通常可以直接从 `@cf-wasm/photon` 让运行时间选择正确的入站点 :

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

如果您想要明确, 请从子模块导入 :

-   Cloudflare Workers / Pages (Wrangler): 云花工/页面(英语:
    
    ```ts
    import { PhotonImage } from "@cf-wasm/photon/workerd";
    ```
    
-   Next.js Edge 运行时间 :
    
    ```ts
    import { PhotonImage } from "@cf-wasm/photon/edge-light";
    ```
    
-   节点.js(内含):
    
    ```ts
    import { PhotonImage } from "@cf-wasm/photon/node";
    ```
    
-   浏览器, Web Worker等(实验)
    
    ```ts
    import { PhotonImage } from "@cf-wasm/photon/others";
    ```
    

> \[尖叫声\] 云花板工人有严格的记忆盖(典型的) `128MB`) (中文(简体) ). 为了避免超过这些限制,在处理前验证输入图像大小或拒绝超大小的图像.

## 实例

以下是图像被调整大小并转换为webp格式的一些例子:

### 云花岗工人

使用Cloudflare Workers的,可以使用如下: 1

```ts
// 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路由器) (英语)

如果您正在使用 Next.js (App 路由器) 的边缘运行时间,您可以使用如下:

```ts
// (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 (页路由器)

如果您正在使用 Next.js (Pages 路由器) 的边缘运行时间,您可以使用如下:

```ts
// (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",
    },
  });
}
```

### 网络工作者

你用得着 `others` 并使用 `initPhoton` 函数使其在其他运行时间(即:. `Browser`, (中文(简体) ), `Web Worker`(见e/cn.4/sub.2/2002/l.48等).

> \[尖叫声\] 这个 `others` 子模块尚属实验. 中断修改可以不遵循语义版本而引入.

[@ deox/ worker- rpc](https://github.com/kumardeo/deox/tree/main/packages/worker-rpc) 在使用网络工作人员时,可以使信息更加容易.

以下是Webpack捆绑器使用Webpack捆绑器时Web Workers的工作例子:

创建一个 `worker.ts`数字 :

```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;
```

现在你可以在你的入口处使用:

```ts
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;
  });
```

## 文档

为了探索所有功能,访问 [正式文件](https://docs.rs/photon-rs/)。 。 。 .

## 报告问题

这个图书馆是一个叉子 [`silvia-odwyer/photon`](https://github.com/silvia-odwyer/photon),因此考虑在此开始讨论问题或专题请求.

对于WebAssembly相关议题,您可在此存储器中打开一个议题.

## 优秀项目

以下是使用此库构建的项目列表:

-   [下一个图像处理 API](https://github.com/yoeven/next-image-processing-api) (按 [约文·克姆兰尼](https://github.com/yoeven)(中文(简体) )

## 贷项

所有功劳都归于 [@silvia-odwyer/图片](https://github.com/silvia-odwyer/photon)。 。 。 .

## 常见问题

### @cf-wasm/photon 是什么？

为Cloudflare工作的光子图书馆,Next\.js和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 和提交记录判断。

