From d9d416a0fe655033be1430817994b00803b75b02 Mon Sep 17 00:00:00 2001 From: xzeldon Date: Tue, 17 Oct 2023 20:12:28 +0300 Subject: [PATCH] initial impl --- Cargo.toml | 1 + src/lib.rs | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 54 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 426a0b4..cf5f3f7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,7 @@ edition = "2021" crate-type = ["cdylib"] [dependencies] +magick_rust = "0.19.1" napi = "2.13.3" napi-derive = "2.13.0" diff --git a/src/lib.rs b/src/lib.rs index e0cc18c..8e4fb7d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,8 +1,59 @@ #![deny(clippy::all)] +use magick_rust::{magick_wand_genesis, MagickWand}; +use napi::{ + bindgen_prelude::{AsyncTask, Buffer}, + Task, +}; use napi_derive::napi; +use std::sync::Once; + +static START: Once = Once::new(); + +struct LiquidRescale { + input: Buffer, +} #[napi] -pub fn plus_100(input: u32) -> u32 { - input + 100 +impl Task for LiquidRescale { + type Output = Buffer; + type JsValue = Buffer; + + fn compute(&mut self) -> napi::Result { + let buffer: Vec = self.input.clone().into(); + let result = lib_liquid_rescale(&buffer, 200, 400).unwrap(); + Ok(result.into()) + } + + fn resolve(&mut self, _env: napi::Env, output: Self::Output) -> napi::Result { + Ok(output) + } +} + +#[napi(js_name = "liquidRescaleImage")] +fn liquid_rescale(input_image: Buffer) -> AsyncTask { + AsyncTask::new(LiquidRescale { input: input_image }) +} + +fn lib_liquid_rescale(input_image: &[u8], width: usize, height: usize) -> Result, String> { + START.call_once(|| { + magick_wand_genesis(); + }); + + let wand = MagickWand::new(); + + if let Err(err) = wand.read_image_blob(input_image) { + return Err(format!("Failed to read image: {}", err)); + } + + if let Err(err) = wand.liquid_rescale_image(width, height, 1.0, 0.0) { + return Err(format!("Failed to perform liquid rescaling: {}", err)); + } + + let output_image = match wand.write_image_blob("JPEG") { + Ok(image) => image, + Err(err) => return Err(format!("Failed to write image: {}", err)), + }; + + Ok(output_image) }