边缘函数

图像处理


Supabase Storage 为最常见的图像转换和优化提供了开箱即用的支持。如果您需要执行超出 Supabase Storage 提供的自定义操作,可以使用边缘函数编写自定义图像处理脚本。

在本示例中,我们将使用 magick-wasm 进行图像处理。magick-wasm 是流行的 ImageMagick 库的 WebAssembly 移植版本,支持处理超过 100 种文件格式。

先决条件

确保已安装最新版本的 Supabase CLI

创建边缘函数

在本地创建新函数:

1
supabase functions new image-blur

编写函数

在本示例中,我们将实现一个允许用户上传图像并获取模糊缩略图的函数。

以下是 index.ts 文件中的实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// This is an example showing how to use Magick WASM to do image manipulations in Edge Functions.//import { ImageMagick, initializeImageMagick, MagickFormat,} from "npm:@imagemagick/magick-wasm@0.0.30";const wasmBytes = await Deno.readFile( new URL( "magick.wasm", import.meta.resolve("npm:@imagemagick/magick-wasm@0.0.30"), ),);await initializeImageMagick( wasmBytes,);Deno.serve(async (req) => { const formData = await req.formData(); const content = await formData.get("file").bytes(); let result = ImageMagick.read( content, (img): Uint8Array => { // resize the image img.resize(500, 300); // add a blur of 60x5 img.blur(60, 5); return img.write( (data) => data, ); }, ); return new Response( result, { headers: { "Content-Type": "image/png" } }, );});
View source

本地测试

您可以通过以下命令在本地测试该函数:

1
2
supabase startsupabase functions serve --no-verify-jwt

然后使用 curl 或您喜欢的 API 测试工具发起请求:

1
2
3
curl --location '<http://localhost:54321/functions/v1/image-blur>' \\--form 'file=@"/path/to/image.png"'--output '/path/to/output.png'

如果打开 output.png 文件,您将看到原始图像的转换版本。

部署到托管项目

现在,让我们将函数部署到您的 Supabase 项目中。

1
2
supabase linksupabase functions deploy image-blur