forked from rxing-core/rxing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsvg_luminance_source.rs
85 lines (68 loc) · 2.5 KB
/
svg_luminance_source.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use crate::{BufferedImageLuminanceSource, Exceptions, LuminanceSource};
use image::{DynamicImage, RgbaImage};
use resvg::{self, usvg::Options};
pub struct SVGLuminanceSource(BufferedImageLuminanceSource);
impl LuminanceSource for SVGLuminanceSource {
fn getRow(&self, y: usize) -> Vec<u8> {
self.0.getRow(y)
}
fn getMatrix(&self) -> Vec<u8> {
self.0.getMatrix()
}
fn getWidth(&self) -> usize {
self.0.getWidth()
}
fn getHeight(&self) -> usize {
self.0.getHeight()
}
fn invert(&mut self) {
self.0.invert()
}
fn isCropSupported(&self) -> bool {
self.0.isCropSupported()
}
fn crop(
&self,
left: usize,
top: usize,
width: usize,
height: usize,
) -> Result<Box<dyn LuminanceSource>, Exceptions> {
self.0.crop(left, top, width, height)
}
fn isRotateSupported(&self) -> bool {
self.0.isRotateSupported()
}
fn rotateCounterClockwise(&self) -> Result<Box<dyn LuminanceSource>, Exceptions> {
self.0.rotateCounterClockwise()
}
fn rotateCounterClockwise45(&self) -> Result<Box<dyn LuminanceSource>, Exceptions> {
self.0.rotateCounterClockwise45()
}
}
impl SVGLuminanceSource {
pub fn new(svg_data: &[u8]) -> Result<Self, Exceptions> {
// Load the SVG file
let Ok(tree) = resvg::usvg::Tree::from_data(svg_data, &Options::default()) else {
return Err(Exceptions::FormatException(Some(format!("could not parse svg data: {}", "err"))));
};
let Some(mut pixmap) = resvg::tiny_skia::Pixmap::new(tree.size.width() as u32, tree.size.height() as u32) else {
return Err(Exceptions::FormatException(Some("could not create pixmap".to_owned())));
};
resvg::render(
&tree,
resvg::usvg::FitTo::Original,
resvg::tiny_skia::Transform::default(),
pixmap.as_mut(),
);
let Some(buffer) = RgbaImage::from_raw(tree.size.width() as u32, tree.size.height() as u32, pixmap.data().to_vec()) else {
return Err(Exceptions::FormatException(Some("could not create image buffer".to_owned())));
};
// let Ok(image) = image::load_from_memory_with_format(pixmap.data(), image::ImageFormat::Bmp) else {
// return Err(Exceptions::FormatException(Some("could not generate image".to_owned())));
// };
Ok(Self(BufferedImageLuminanceSource::new(DynamicImage::from(
buffer,
))))
}
}