Created
June 2, 2024 07:52
-
-
Save olddustysocksunderthecouch/12c3d2333b04aaff62a9e17f5e8a9e2f to your computer and use it in GitHub Desktop.
Generate Base64 Thumbhash with a Supabase Edge Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { SupabaseClient } from "https://esm.sh/@supabase/[email protected]"; | |
import { rgbaToThumbHash } from "https://esm.sh/[email protected]"; | |
import { Image, decode } from "https://deno.land/x/[email protected]/mod.ts"; | |
import * as base64 from "https://denopkg.com/chiefbiiko/base64/mod.ts"; | |
async function generateBase64ThumbHash( | |
data: ArrayBuffer, | |
): Promise<string> { | |
const image = await decode(new Uint8Array(data)) as Image; | |
image.resize(100, 100); | |
if (!image) { | |
throw new Error("Failed to decode the image"); | |
} | |
const hash = rgbaToThumbHash(image.width, image.height, image.bitmap); | |
const thumbhash = base64.fromUint8Array(hash); | |
return thumbhash; | |
} | |
export async function ImageUrlToBase64ThumbHash( | |
supabaseClient: SupabaseClient, | |
url: string, | |
): Promise<{string}> { | |
const response = await fetch(url); | |
const data = await response.arrayBuffer(); | |
return (await generateBase64ThumbHash(data)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I struggled to get this working for ages, so I hope this saves you time.
For context, I wanted to implement thumbhash in my React Native expo app. The expo-image package can use thumbhash as a placeholder.