Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save olddustysocksunderthecouch/12c3d2333b04aaff62a9e17f5e8a9e2f to your computer and use it in GitHub Desktop.
Save olddustysocksunderthecouch/12c3d2333b04aaff62a9e17f5e8a9e2f to your computer and use it in GitHub Desktop.
Generate Base64 Thumbhash with a Supabase Edge Function
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));
}
@olddustysocksunderthecouch
Copy link
Author

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.

import { Image } from 'expo-image'
// ...
<Image
              source={{
                uri: publicUrl,
              }}
              placeholder={{ thumbhash }}
            />
          )}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment