1use crate::{load::load_image, source_type::SourceType};
2
3#[cfg(feature = "wasm")]
4use {
5 js_sys::Uint8Array,
6 wasm_bindgen::prelude::*,
7};
8
9#[cfg(not(feature = "wasm"))]
10use crate::error::WasmImageError;
11
12#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
13#[cfg_attr(feature = "wasm", tsify(from_wasm_abi, into_wasm_abi))]
14#[derive(serde::Serialize, serde::Deserialize, Default)]
15pub struct ImageData {
16 pub width: u32,
17 pub height: u32,
18 pub aspect_ratio: f32,
19 pub color_depth: u16,
20 pub pixels: Vec<u8>,
21}
22
23#[cfg(feature = "wasm")]
24#[wasm_bindgen(js_name = getPixels)]
25pub fn get_pixels(file: &Uint8Array, src_type: &str) -> Result<ImageData, JsValue> {
34 let src_mime_type = SourceType::from_mime_type(src_type);
35
36 let file = file.to_vec();
37
38 let img = load_image(&file, src_mime_type.as_ref())
39 .map_err(|e| JsValue::from_str(e.to_string().as_str()))?
40 .rasterize(None)
41 .map_err(|e| JsValue::from_str(e.to_string().as_str()))?;
42
43 let pixels = img.to_rgba8().into_vec();
44
45 let color_depth = match src_mime_type {
46 Some(SourceType::Svg) => 32,
47 _ => img.color().bits_per_pixel(),
48 };
49
50 Ok(ImageData {
51 width: img.width(),
52 height: img.height(),
53 aspect_ratio: img.width() as f32 / img.height() as f32,
54 color_depth,
55 pixels,
56 })
57}
58
59#[cfg(not(feature = "wasm"))]
60pub fn get_pixels(file: &[u8], src_type: &str) -> Result<ImageData, WasmImageError> {
69 let src_mime_type = SourceType::from_mime_type(src_type);
70
71 let img = load_image(file, src_mime_type.as_ref())?
72 .rasterize(None)?;
73
74 let pixels = img.to_rgba8().into_vec();
75
76 let color_depth = match src_mime_type {
77 Some(SourceType::Svg) => 32,
78 _ => img.color().bits_per_pixel(),
79 };
80
81 Ok(ImageData {
82 width: img.width(),
83 height: img.height(),
84 aspect_ratio: img.width() as f32 / img.height() as f32,
85 color_depth,
86 pixels,
87 })
88}