Debian Codegraph @

src/convert/svg.rs

raw symbols SCIP
1 //! Converts [`QRCode`] to SVG
2 //!
3 //! ```rust
4 //! use fast_qr::convert::ConvertError;
5 //! use fast_qr::convert::{svg::SvgBuilder, Builder, Shape};
6 //! use fast_qr::qr::QRBuilder;
7 //!
8 //! # fn main() -> Result<(), ConvertError> {
9 //! // QRBuilde::new can fail if content is too big for version,
10 //! // please check before unwrapping.
11 //! let qrcode = QRBuilder::new("https://example.com/")
12 //! .build()
13 //! .unwrap();
14 //!
15 //! let _svg = SvgBuilder::default()
16 //! .shape(Shape::RoundedSquare)
17 //! .to_file(&qrcode, "out.svg");
18 //!
19 //! # std::fs::remove_file("out.svg");
20 //! # Ok(())
21 //! # }
22 //! ```
23
24 use crate::{QRCode, Version};
25
26 use super::{Builder, Color, ImageBackgroundShape, ModuleFunction, Shape};
27
28 /// Builder for svg, can set shape, margin, background_color, dot_color
29 pub struct SvgBuilder {
30 /// Command vector allows predefined or custom shapes
31 /// The default is square, commands can be added using `.shape()`
32 commands: Vec<ModuleFunction>,
33 /// Commands can also have a custom color
34 /// The default is `dot_color`, commands with specific colors can be
35 /// added using `.shape_color()`
36 command_colors: Vec<Option<Color>>,
37 /// The margin for the svg, default is 4
38 margin: usize,
39 /// The background color for the svg, default is #FFFFFF
40 background_color: Color,
41 /// The color for each module, default is #000000
42 dot_color: Color,
43
44 // Image Embedding
45 /// Image to embed in the svg, can be a path or a base64 string
46 image: Option<String>,
47 /// Background color for the image, default is #FFFFFF
48 image_background_color: Color,
49 /// Background shape for the image, default is square
50 image_background_shape: ImageBackgroundShape,
51 /// Size of the image (in module size), default is ~1/3 of the svg
52 image_size: Option<f64>,
53 /// Gap between the image and the border (in module size), default is calculated
54 image_gap: Option<f64>,
55 /// Position of the image, default is center
56 image_position: Option<(f64, f64)>,
57 }
58
59 #[derive(Debug)]
60 /// Possible errors when converting to SVG
61 pub enum SvgError {
62 /// Error while writing file
63 #[cfg(not(feature = "wasm-bindgen"))]
64 IoError(std::io::Error),
65 /// Error while creating svg
66 SvgError(String),
67 }
68
69 /// Creates a Builder instance
70 impl Default for SvgBuilder {
71 fn default() -> Self {
72 SvgBuilder {
73 background_color: [255; 4].into(),
74 dot_color: [0, 0, 0, 255].into(),
75 margin: 4,
76 commands: Vec::new(),
77 command_colors: Vec::new(),
78
79 // Image Embedding
80 image: None,
81 image_background_color: [255; 4].into(),
82 image_background_shape: ImageBackgroundShape::Square,
83 image_size: None,
84 image_gap: None,
85 image_position: None,
86 }
87 }
88 }
89
90 impl Builder for SvgBuilder {
91 fn margin(&mut self, margin: usize) -> &mut Self {
92 self.margin = margin;
93 self
94 }
95
96 fn module_color<C: Into<Color>>(&mut self, dot_color: C) -> &mut Self {
97 self.dot_color = dot_color.into();
98 self
99 }
100
101 fn background_color<C: Into<Color>>(&mut self, background_color: C) -> &mut Self {
102 self.background_color = background_color.into();
103 self
104 }
105
106 fn shape(&mut self, shape: Shape) -> &mut Self {
107 self.commands.push(*shape);
108 self.command_colors.push(None);
109 self
110 }
111
112 fn shape_color<C: Into<Color>>(&mut self, shape: Shape, color: C) -> &mut Self {
113 self.commands.push(*shape);
114 self.command_colors.push(Some(color.into()));
115 self
116 }
117
118 fn image(&mut self, image: String) -> &mut Self {
119 self.image = Some(image);
120 self
121 }
122
123 fn image_background_color<C: Into<Color>>(&mut self, image_background_color: C) -> &mut Self {
124 self.image_background_color = image_background_color.into();
125 self
126 }
127
128 fn image_background_shape(
129 &mut self,
130 image_background_shape: ImageBackgroundShape,
131 ) -> &mut Self {
132 self.image_background_shape = image_background_shape;
133 self
134 }
135
136 fn image_size(&mut self, image_size: f64) -> &mut Self {
137 self.image_size = Some(image_size);
138 self
139 }
140
141 fn image_gap(&mut self, gap: f64) -> &mut Self {
142 self.image_gap = Some(gap);
143 self
144 }
145
146 fn image_position(&mut self, x: f64, y: f64) -> &mut Self {
147 self.image_position = Some((x, y));
148 self
149 }
150 }
151
152 impl SvgBuilder {
153 fn image_placement(image_background_shape: ImageBackgroundShape, n: usize) -> (f64, f64) {
154 use ImageBackgroundShape::{Circle, RoundedSquare, Square};
155
156 #[rustfmt::skip]
157 const SQUARE: [f64; 40] = [
158 5f64, 9f64, 9f64, 11f64, 13f64,
159 13f64, 15f64, 17f64, 17f64, 19f64,
160 21f64, 21f64, 23f64, 25f64, 25f64,
161 27f64, 29f64, 29f64, 31f64, 33f64,
162 33f64, 35f64, 37f64, 37f64, 39f64,
163 41f64, 41f64, 43f64, 45f64, 45f64,
164 47f64, 49f64, 49f64, 51f64, 53f64,
165 53f64, 55f64, 57f64, 57f64, 59f64,
166 ];
167 const ROUNDED_SQUARE: [f64; 40] = SQUARE;
168 const CIRCLE: [f64; 40] = SQUARE;
169
170 // Using hardcoded values
171 let version = Version::from_n(n) as usize;
172 let border_size = match image_background_shape {
173 Square => SQUARE[version],
174 RoundedSquare => ROUNDED_SQUARE[version],
175 Circle => CIRCLE[version],
176 };
177
178 // Allows for a module gap between the image and the border
179 let gap = match image_background_shape {
180 Square | RoundedSquare => 2f64,
181 Circle => 3f64,
182 };
183 // Make the image border bigger for bigger versions
184 let gap = gap * (version + 10) as f64 / 10f64;
185 (border_size, (border_size - gap).round())
186 }
187
188 fn image(&self, n: usize) -> String {
189 if self.image.is_none() {
190 return String::new();
191 }
192
193 let image = self.image.as_ref().unwrap();
194 let mut out = String::with_capacity(image.len() + 100);
195
196 let (mut border_size, mut image_size) =
197 Self::image_placement(self.image_background_shape, n);
198
199 if let Some(override_size) = self.image_size {
200 let gap = -(image_size - border_size);
201 border_size = override_size + gap;
202 image_size = override_size;
203 }
204
205 if let Some(override_gap) = self.image_gap {
206 border_size = image_size + override_gap * 2f64;
207 }
208
209 let mut placed_coord_x = (self.margin * 2 + n) as f64 - border_size;
210
211 // Adjust for non-integer initial x coordinates so as not to partially cover bits by rounding down.
212 if placed_coord_x % 2f64 != 0f64 {
213 placed_coord_x += 1f64;
214 border_size -= 1f64;
215 }
216
217 placed_coord_x /= 2f64;
218
219 let mut placed_coord = (placed_coord_x, placed_coord_x);
220
221 if let Some((x, y)) = self.image_position {
222 placed_coord = (x - border_size / 2f64, y - border_size / 2f64);
223 }
224
225 let format = match self.image_background_shape {
226 ImageBackgroundShape::Square => {
227 r#"<rect x="{0}" y="{1}" width="{2}" height="{2}" fill="{3}"/>"#
228 }
229 ImageBackgroundShape::Circle => {
230 r#"<rect x="{0}" y="{1}" width="{2}" height="{2}" fill="{3}" rx="1000px"/>"#
231 }
232 ImageBackgroundShape::RoundedSquare => {
233 r#"<rect x="{0}" y="{1}" width="{2}" height="{2}" fill="{3}" rx="1px"/>"#
234 }
235 };
236
237 let format = format
238 .replace("{0}", &placed_coord.0.to_string())
239 .replace("{1}", &placed_coord.1.to_string())
240 .replace("{2}", &border_size.to_string())
241 .replace("{3}", self.image_background_color.to_str());
242
243 out.push_str(&format);
244
245 out.push_str(&format!(
246 r#"<image x="{0:.2}" y="{1:.2}" width="{2:.2}" height="{2:.2}" href="{3}" />"#,
247 placed_coord.0 + (border_size - image_size) / 2f64,
248 placed_coord.1 + (border_size - image_size) / 2f64,
249 image_size,
250 image
251 ));
252
253 out
254 }
255
256 fn path(&self, qr: &QRCode) -> String {
257 const DEFAULT_COMMAND: [ModuleFunction; 1] = [Shape::square];
258 const DEFAULT_COMMAND_COLOR: [Option<Color>; 1] = [None];
259
260 // TODO: cleanup this basic logic
261 let command_colors: &[Option<Color>] = if !self.commands.is_empty() {
262 &self.command_colors
263 } else {
264 &DEFAULT_COMMAND_COLOR
265 };
266 let commands: &[ModuleFunction] = if !self.commands.is_empty() {
267 &self.commands
268 } else {
269 &DEFAULT_COMMAND
270 };
271
272 let mut paths = vec![String::with_capacity(10 * qr.size * qr.size); commands.len()];
273 for path in paths.iter_mut() {
274 path.push_str(r#"<path d=""#);
275 }
276
277 for y in 0..qr.size {
278 let line = &qr[y];
279 for (x, &cell) in line.iter().enumerate() {
280 if !cell.value() {
281 continue;
282 }
283
284 for (i, command) in commands.iter().enumerate() {
285 paths[i].push_str(&command(y + self.margin, x + self.margin, cell));
286 }
287 }
288 }
289
290 for (i, &command) in commands.iter().enumerate() {
291 let command_color = command_colors[i].as_ref().unwrap_or(&self.dot_color);
292 // Allows to compare if two function pointers are the same
293 // This works because there is no notion of Generics for `rounded_square`
294 if command as usize == Shape::rounded_square as usize {
295 paths[i].push_str(&format!(
296 r##"" stroke-width=".3" stroke-linejoin="round" stroke="{}"##,
297 command_color.to_str()
298 ));
299 }
300
301 paths[i].push_str(&format!(r#"" fill="{}"/>"#, command_color.to_str()));
302 }
303
304 paths.join("")
305 }
306
307 /// Return a string containing the svg for a qr code
308 pub fn to_str(&self, qr: &QRCode) -> String {
309 let n = qr.size;
310
311 let mut out = String::with_capacity(11 * n * n / 2);
312 out.push_str(&format!(
313 r#"<svg viewBox="0 0 {0} {0}" xmlns="http://www.w3.org/2000/svg">"#,
314 self.margin * 2 + n
315 ));
316
317 out.push_str(&format!(
318 r#"<rect width="{0}px" height="{0}px" fill="{1}"/>"#,
319 self.margin * 2 + n,
320 self.background_color.to_str()
321 ));
322
323 out.push_str(&self.path(qr));
324 out.push_str(&self.image(n));
325
326 out.push_str("</svg>");
327 out
328 }
329
330 /// Saves the svg for a qr code to a file
331 #[cfg(not(feature = "wasm-bindgen"))]
332 pub fn to_file(&self, qr: &QRCode, file: &str) -> Result<(), SvgError> {
333 use std::fs::File;
334 use std::io::Write;
335
336 let out = self.to_str(qr);
337
338 let mut f = File::create(file).map_err(SvgError::IoError)?;
339 f.write_all(out.as_bytes()).map_err(SvgError::IoError)?;
340
341 Ok(())
342 }
343 }