基于rust实现Floyd Steinberg效果

242 阅读1分钟
use image::{DynamicImage, ImageBuffer};
use wasm_bindgen::prelude::*;
use web_sys::ImageData;

#[wasm_bindgen]
pub fn floyd_steinberg(image_data: ImageData) -> Vec<u8> {
    let width = image_data.width();
    let height = image_data.height();
    let raw_pixels = image_data.data().to_vec();
    _floyd_steinberg(width, height, raw_pixels)
}

fn _floyd_steinberg(width: u32, height: u32, data: Vec<u8>) -> Vec<u8> {
    let image_buf = ImageBuffer::from_vec(width, height, data).unwrap();
    let image = DynamicImage::ImageRgba8(image_buf);
    let raw_pixels = image.to_luma8().to_vec();
    let color_map = image::imageops::colorops::BiLevel;
    let mut img_buffer = ImageBuffer::from_vec(width, height, raw_pixels).unwrap();
    image::imageops::colorops::dither(&mut img_buffer, &color_map);
    let dither_img = image::DynamicImage::ImageLuma8(img_buffer);
    dither_img.to_rgba8().to_vec()
}

结果:

微信图片_20221022085044.png

更多效果查看: yirandidi.github.io/yr_rust_kon…

源码:github.com/yirandidi/y…