From ad72d2582eeab9e043d797f98e49785327211df2 Mon Sep 17 00:00:00 2001 From: waltem01 Date: Fri, 16 Feb 2024 07:18:53 +0100 Subject: [PATCH] read image, create data url --- Webserver/src/routes/image/+page.svelte | 31 +++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/Webserver/src/routes/image/+page.svelte b/Webserver/src/routes/image/+page.svelte index 1fb12b2..24d5f32 100644 --- a/Webserver/src/routes/image/+page.svelte +++ b/Webserver/src/routes/image/+page.svelte @@ -10,7 +10,31 @@ let imageURL: string | null, lastImage: File; let uploadData: UploadData; - async function sendImage() {} + async function fileAsDataURL(file: File, width: number, height: number): Promise { + return new Promise((resolve, reject) => { + const img = new Image(); + img.onload = () => { + const canvas = document.createElement('canvas'); + const context = canvas.getContext('2d'); + + // Set the canvas dimensions + canvas.width = width; + canvas.height = height; + + // Draw the image onto the canvas, resizing it to fit the canvas + context?.drawImage(img, 0, 0, width, height); + + // Convert the canvas image to a Data URL + const dataURL = canvas.toDataURL(); + resolve(dataURL); + }; + img.onerror = reject; + + // Create an object URL for the file and set it as the image source + const objectURL = URL.createObjectURL(file); + img.src = objectURL; + }); + } function uploadImage(event: Event) { // Revoke previous image url, if any @@ -46,12 +70,11 @@ {#if imageURL} User uploaded - {#await sendImage()} -

Sending image . . .

+ {#await fileAsDataURL(lastImage, 192, 192)} +

Loading image data . . .

{uploadData.elapsed} seconds elapsed.

{:then}

Done!

{uploadData.elapsed} seconds elapsed.

- {clearInterval(uploadData.interval)} {/await} {/if}