From 6816585d613a6df4ae10eadcb8e8af9b81666d03 Mon Sep 17 00:00:00 2001 From: CrispyBaguette Date: Sat, 11 Dec 2021 17:54:15 +0100 Subject: [PATCH] Handle images as Blobs --- client/src/App.tsx | 10 ++++++---- src/wasm.go | 17 ++++++++++++----- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/client/src/App.tsx b/client/src/App.tsx index 37eadfb..2c1d49c 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -10,7 +10,6 @@ function App() { return; } const workerProxy: any = await wasmWorker("main.wasm"); - setImageSrc(""); // Check if a file was selected @@ -23,9 +22,12 @@ function App() { reader.onloadend = async (evt) => { if (evt.target!.readyState === FileReader.DONE) { const imageData = new Uint8Array(evt.target!.result as ArrayBuffer); - const ditheredImage = await workerProxy.DitherNord(imageData); - const outputValue = `data:image/png;base64,${ditheredImage}`; - setImageSrc(outputValue); + const ditheredImageArray = await workerProxy.DitherNord(imageData); + const imageBlob = new Blob([ditheredImageArray.buffer], { + type: "image/png", + }); + const url = URL.createObjectURL(imageBlob); + setImageSrc(url); } }; }; diff --git a/src/wasm.go b/src/wasm.go index 67524c8..0df7edf 100644 --- a/src/wasm.go +++ b/src/wasm.go @@ -2,7 +2,6 @@ package main import ( "bytes" - b64 "encoding/base64" "encoding/hex" "image" "image/color" @@ -69,7 +68,7 @@ func decodeImage(imageData []byte) (image.Image, error) { } // DittherNord returns a Promise that takes a UintArray containing a Jpeg or png image, -// and resolves to a string containing a base64 encoded png image. +// and resolves to a UintArray containing the dithered image. func DitherNord() js.Func { return js.FuncOf(func(this js.Value, args []js.Value) interface{} { imageBytes := make([]byte, args[0].Length()) @@ -96,12 +95,20 @@ func DitherNord() js.Func { log.Printf("Image dithered in %v\n", t2.Sub(t1)) // Encode as PNG + log.Println("Encoding image...") + t1 = time.Now() buf := new(bytes.Buffer) png.Encode(buf, ditheredImage) + t2 = time.Now() + log.Printf("Image encoded in %v\n", t2.Sub(t1)) - // Encode as img src b64 string and resolve - encodedImage := b64.StdEncoding.EncodeToString(buf.Bytes()) - resolve.Invoke(js.ValueOf(encodedImage)) + log.Println("Copying image to JS...") + t1 = time.Now() + encodedImage := js.Global().Get("Uint8ClampedArray").New(len(buf.Bytes())) + js.CopyBytesToJS(encodedImage, buf.Bytes()) + t2 = time.Now() + log.Printf("Image copied in %v\n", t2.Sub(t1)) + resolve.Invoke(encodedImage) }() return nil