rust_wasm_dev_helper/
lib.rs

1mod utils;
2#[macro_use]
3mod log;
4
5use wasm_bindgen::prelude::*;
6use image::{ImageBuffer, Rgb, png::PngDecoder, ImageFormat, RgbImage};
7use std::io::{Cursor, Seek, SeekFrom, Read};
8use wasm_bindgen::__rt::IntoJsResult;
9
10// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
11// allocator.
12#[cfg(feature = "wee_alloc")]
13#[global_allocator]
14static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
15
16#[wasm_bindgen]
17extern {
18    fn alert(s: &str);
19}
20
21#[wasm_bindgen]
22pub fn greet() {
23    alert("Hello, rust-wasm-dev-helper!");
24}
25
26#[wasm_bindgen]
27pub fn create_img(width: u32, height: u32, r: u8, g: u8, b: u8) -> Vec<u8> {
28
29    // reset width and height
30    let width = match width {
31        0 => 100,
32        _ => width,
33    };
34    let height = match height {
35        0 => 100,
36        _ => height,
37    };
38    let img_path = format!("gen-png/gen-{}_{}-{}_{}_{}.png", width, height, r, g, b);
39
40    std::fs::read(img_path.clone()).unwrap_or_else(|_| {
41        let mut img: RgbImage = RgbImage::new(width, height);
42        for mut px in img.enumerate_pixels_mut().enumerate() {
43            (((px.1).2).0)[0] = r;
44            (((px.1).2).0)[1] = g;
45            (((px.1).2).0)[2] = b;
46        }
47        std::fs::create_dir("gen-png").unwrap_or_default();
48        img.save(img_path.clone()).unwrap();
49        std::fs::read(img_path).unwrap_or_default()
50    })
51}
52
53#[cfg(test)]
54mod tests {
55    use crate::create_img;
56
57    #[test]
58    pub fn test() {
59        println!("{:?}", create_img(375, 250, 0, 0, 0))
60    }
61}