Wasm-bindgen: How do I read? transport? png file from js to rust(wasm)

Created on 26 Oct 2019  路  3Comments  路  Source: rustwasm/wasm-bindgen

Summary

I don't know how to read png file at rust(wasm).
I want to know it because I will make apng maker on wasm web application.

question

Most helpful comment

An image may be represented as an ArrayBuffer in JS. For example, we can create a png from a canvas context using toBlob() method with 'image/png' type. Blob has a method arrayBuffer(). Finally, we can have

let data = new Uint8Array(arrayBufferFromBlob);
wasm.processImage(data);

where in Rust it will look like

#[wasm_bindgen(js_name = processImage)]
pub fn process_image(data: Vec<u8>) {
   let result = image::load_from_memory_with_format(&data, image::ImageFormat::PNG);
   ...
}

Docs link for load_from_memory_with_format

All 3 comments

An image may be represented as an ArrayBuffer in JS. For example, we can create a png from a canvas context using toBlob() method with 'image/png' type. Blob has a method arrayBuffer(). Finally, we can have

let data = new Uint8Array(arrayBufferFromBlob);
wasm.processImage(data);

where in Rust it will look like

#[wasm_bindgen(js_name = processImage)]
pub fn process_image(data: Vec<u8>) {
   let result = image::load_from_memory_with_format(&data, image::ImageFormat::PNG);
   ...
}

Docs link for load_from_memory_with_format

@ibaryshnikov
Thank you for this solution.
Can I also use this to return image buf from rust to js?

I think that @ibaryshnikov has this covered, and yes @poccariswet you can also return a Vec<u8> or a Uint8Array

Was this page helpful?
0 / 5 - 0 ratings