From c09237e112625c1a5e655f4994d5a85aadd59768 Mon Sep 17 00:00:00 2001 From: Christoph Urlacher Date: Mon, 16 Dec 2024 13:35:45 +0100 Subject: [PATCH] Lib: Add function to fetch image as base64 string --- src/lib/image.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/lib/image.ts b/src/lib/image.ts index 68447e2..3eb7ba4 100644 --- a/src/lib/image.ts +++ b/src/lib/image.ts @@ -45,3 +45,22 @@ export const get_image_preview_event_handler = (id: string): ((event: Event) => return handler; }; + +/** Convert a binary [Blob] to base64 string */ +export const blob_to_base64 = (blob: Blob): Promise => { + return new Promise((resolve, _) => { + const reader = new FileReader(); + + // This is fired once the file read has ended + reader.onloadend = () => resolve(reader.result?.toString() ?? ""); + + reader.readAsDataURL(blob); + }); +}; + +/** Fetch an image from an URL using a fetch function [f] and return as base64 string */ +export const fetch_image_base64 = async (url: string, f: Function = fetch): Promise => { + return f(url) + .then((response: Response) => response.blob()) + .then((blob: Blob) => blob_to_base64(blob)); +};