Image Manipulation
Supabase Storage has out-of-the-box support for the most common image transformations and optimizations you need. If you need to do anything custom beyond what Supabase Storage provides, you can use Edge Functions to write custom image manipulation scripts.
In this example, we will use magick-wasm to perform image manipulations. magick-wasm is the WebAssembly port of the popular ImageMagick library and supports processing over 100 file formats.
Edge Functions currently doesn't support image processing libraries such as Sharp, which depend on native libraries. Only WASM-based libraries are supported.
Prerequisites#
Make sure you have the latest version of the Supabase CLI installed.
Create the Edge Function#
Create a new function locally:
1supabase functions new image-blurWrite the function#
In this example, we are implementing a function allowing users to upload an image and get a blurred thumbnail.
Here's the implementation in index.ts file:
1// This is an example showing how to use Magick WASM to do image manipulations in Edge Functions.2//3import { ImageMagick, initializeImageMagick, MagickFormat } from 'npm:@imagemagick/magick-wasm@^0'4import { withSupabase } from 'npm:@supabase/server@^1'56const wasmBytes = await Deno.readFile(7 new URL('magick.wasm', import.meta.resolve('npm:@imagemagick/magick-wasm@^0'))8)9await initializeImageMagick(wasmBytes)1011// Authenticated endpoint, so deploy with verify_jwt = true.12export default {13 fetch: withSupabase({ auth: 'user' }, async (req, _ctx) => {14 const formData = await req.formData()15 const file = formData.get('file')16 if (!(file instanceof Blob)) {17 return Response.json({ error: 'file is required' }, { status: 400 })18 }19 const content = await file.bytes()2021 let result = ImageMagick.read(content, (img): Uint8Array => {22 // resize the image23 img.resize(500, 300)24 // add a blur of 60x525 img.blur(60, 5)2627 return img.write((data) => data)28 })2930 return new Response(Uint8Array.from(result), {31 headers: { 'Content-Type': 'image/png' },32 })33 }),34}Test it locally#
You can test the function locally by running:
1supabase start2supabase functions serve --no-verify-jwtThen, make a request using curl or your favorite API testing tool.
1curl --location '<http://localhost:54321/functions/v1/image-blur>' \\2--form 'file=@"/path/to/image.png"'3--output '/path/to/output.png'If you open the output.png file you will find a transformed version of your original image.
Deploy to your hosted project#
Deploy the function to your Supabase project.
1supabase link2supabase functions deploy image-blurHosted Edge Functions have limits on memory and CPU usage.
If you try to perform complex image processing or handle large images (> 5MB) your function may return a resource limit exceeded error.