Skip to content

Instantly share code, notes, and snippets.

@udzura
Created December 13, 2024 15:41
Show Gist options
  • Save udzura/513f3f04303ca3f946abe0678c16a1f0 to your computer and use it in GitHub Desktop.
Save udzura/513f3f04303ca3f946abe0678c16a1f0 to your computer and use it in GitHub Desktop.
use core::str;
use core::slice::from_raw_parts;
use base64::{engine::general_purpose, Engine};
use image::{codecs::png, load_from_memory_with_format, ImageBuffer};
#[no_mangle]
pub unsafe fn grayscale(
width: u32, height: u32, src: *const u8, slen: i32,
) -> *const u8 {
let src = from_raw_parts(src, slen as usize);
let mut tmp_buf: Vec<u8> = Vec::<u8>::new();
tmp_buf.resize(slen as usize, 0);
tmp_buf.copy_from_slice(src);
let mut result_buf: Vec<u8> = Vec::<u8>::new();
result_buf.resize(1<<22, 0);
// data url: e.g.
// data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAeAA
// AAFACAYAAABkyK97AAAAAXNSR0IArs4c6QAAIABJREFUeF7svU...
let url = str::from_utf8(&tmp_buf).unwrap();
let collected = url.split(",").collect::<Vec<&str>>();
let src = collected[1].as_bytes();
let blob: Vec<u8> = general_purpose::STANDARD.decode(src).unwrap();
let img: image::DynamicImage = load_from_memory_with_format(&blob, image::ImageFormat::Png).unwrap();
let img: ImageBuffer<image::Rgb<u8>, _> = img.to_rgb8();
let mut dest: ImageBuffer<image::Luma<u8>, Vec<u8>> = image::GrayImage::new(width, height);
for y in 0..height {
for x in 0..width {
let pixel: &image::Rgb<u8> = img.get_pixel(x, y);
// simple avagare
let val = (pixel[0] as f32 + pixel[1] as f32 + pixel[2] as f32) / 3.0;
let val = [val as u8; 1];
dest.put_pixel(x, y, image::Luma(val));
}
}
#[cfg(not(target_arch="wasm32"))]
{
dest.save("/tmp/debug.png").unwrap();
}
let mut inter_buf = Vec::<u8>::new();
let enc = png::PngEncoder::new(&mut inter_buf);
dest.write_with_encoder(enc).unwrap_or_else(|_| panic!("encode failed") );
general_purpose::STANDARD.encode_slice(&inter_buf, &mut result_buf).unwrap();
result_buf.as_ptr()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment