hhhello WebAssembly[rust=>wasm,node]

226 阅读2分钟

开发工具,rustRover,最近公测中,免费体验一把 新建wasm项目

image.png 新建完成差不多是这个样子的

image.png

初始化完成之后 执行命令 wasm-pack build --target nodejs

image.png 点击这个也可打包,但可能不方便使用,相当于执行命令wasm-pack build 打包后会得到这些有用的东西

image.png

把pkg目录复制到你的项目里面(别的安装方式也行)

image.png rust项目默认导出了一个greet的方法,里面调用了alert,但是nodejs里面没有这个方法,所以会报错 稍稍改一下,运行成功

image.png 水文重点,图片拼接代码,拼接逻辑自己写,图片相关用包image 在Cargo.toml添加依赖
[dependencies]
wasm-bindgen = "0.2.91"
image = "0.24.9"

utils.rs添加图片拼接逻辑

pub fn image_combine(img1: DynamicImage, img2: DynamicImage, direction: u8) -> ImageBuffer<Rgba<u8>, Vec<u8>> {
    let width1 = img1.width();
    let height1 = img1.height();
    let width2 = img2.width();
    let height2 = img2.height();

    let (width, height) = if direction == 0 {
        // 竖向拼接
        (if width1 > width2 { width1 } else { width2 }, height1 + height2)
    } else {
        // 横向拼接
        (width1 + width2, if height1 > height2 { height1 } else { height2 })
    };

    let (x, y) = if direction == 0 {
        (0, height1)
    } else {
        (width1, 0)
    };

    let mut new_img = RgbaImage::new(width, height);
    new_img.copy_from(&img1, 0, 0).expect("TODO:panic message");
    new_img.copy_from(&img2, x, y).expect("TODO:panic message");
    new_img
}

lib.rs向外暴露图片拼接接口

#[wasm_bindgen]
pub fn image_combine(image1: Vec<u8>, image2: Vec<u8>, direction: u8) -> Vec<u8> {
    // buffer 转image
    let img1 = image::load_from_memory_with_format(&image1, image::ImageFormat::Png).expect("Failed to load image 1");
    let img2 = image::load_from_memory_with_format(&image2, image::ImageFormat::Png).expect("Failed to load image 2");
    // 合并两个图像
    let combined_img = utils::image_combine(img1, img2, direction);

    let mut bytes: Vec<u8> = Vec::new();
    combined_img.write_to(&mut Cursor::new(&mut bytes), image::ImageOutputFormat::Png).expect("TODO: panic message");
    bytes
}

再次打包在test.js文件添加下面代码

const buffer1 = readFileSync("a.png")
const buffer2 = readFileSync("b.png")

writeFileSync('combined.png', wasm.image_combine(buffer1, buffer2, 0));

node test.js就会出现一张拼接好的图片

参考