Skip to content

Instantly share code, notes, and snippets.

@Takeno
Created July 17, 2025 15:35
Show Gist options
  • Save Takeno/1cc3ee58f68d3ed610447ee2d6bd8b13 to your computer and use it in GitHub Desktop.
Save Takeno/1cc3ee58f68d3ed610447ee2d6bd8b13 to your computer and use it in GitHub Desktop.
Rust into Wasm for Web
  1. Put the lib.rs into src/lib.rs and cargo.toml in the directory root
  2. Compile Rust into WASM with cargo install wasm-pack && wasm-pack build --target web or if you use Docker docker run -it -v "$PWD":/app -w /app rust bash -c "cargo install wasm-pack && wasm-pack build --target web"
  3. Now pkg directory contains the lib
  4. Use it on your browser:
import init, { sum, resize } from "./pkg/app.js";


await init();
console.log(sum(1, 2));


const imageInput = document.getElementById('imageInput');
imageInput.addEventListener('change', async (e) => {
    const file = e.target.files[0];
    const arrayBuffer = await file.arrayBuffer();
    const uint8Array = new Uint8Array(arrayBuffer);
    const resizedImage = resize(uint8Array, 400, 400);

    const blob = new Blob([resizedImage], { type: 'image/png' });
    const url = URL.createObjectURL(blob);
    const img = document.createElement('img');
    img.src = url;
    document.body.appendChild(img);
});
[package]
name = "app"
version = "0.1.0"
edition = "2024"
[dependencies]
image = "0.25.6"
wasm-bindgen = "0.2"
[lib]
crate-type = ["cdylib"]
[dev-dependencies]
wasm-bindgen-test = "0.3"
use wasm_bindgen::prelude::wasm_bindgen;
use std::io::Cursor;
#[wasm_bindgen]
pub fn sum(a: i32, b: i32) -> i32 {
a + b
}
#[wasm_bindgen]
pub fn resize(image_data: &[u8], width: u32, height: u32) -> Vec<u8> {
let image = image::load_from_memory(image_data).expect("Failed to open the file");
let resized_image = image.resize(width, height, image::imageops::FilterType::Lanczos3);
let mut buf = Cursor::new(Vec::new());
resized_image.write_to(&mut buf, image::ImageFormat::Png).expect("Failed to write the image");
buf.into_inner()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment