| 1 | //! Converts [`QRCode`] to an image |
| 2 | //! |
| 3 | //! ```rust |
| 4 | //! use fast_qr::convert::ConvertError; |
| 5 | //! use fast_qr::convert::{image::ImageBuilder, 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 _img = ImageBuilder::default() |
| 16 | //! .shape(Shape::RoundedSquare) |
| 17 | //! .fit_width(600) |
| 18 | //! .to_file(&qrcode, "out.png"); |
| 19 | //! |
| 20 | //! # std::fs::remove_file("out.png"); |
| 21 | //! # Ok(()) |
| 22 | //! # } |
| 23 | //! ``` |
| 24 | |
| 25 | use std::fmt::Formatter; |
| 26 | use std::io; |
| 27 | |
| 28 | use crate::QRCode; |
| 29 | |
| 30 | use super::Color; |
| 31 | use super::{svg::SvgBuilder, Builder, Shape}; |
| 32 | |
| 33 | use resvg::tiny_skia::{self, Pixmap}; |
| 34 | use resvg::usvg::{self, Size, Transform}; |
| 35 | |
| 36 | /// [`ImageBuilder`] contains an [`SvgBuilder`] and adds some options \ |
| 37 | /// - fit_height adds a max-height boundary |
| 38 | /// - fit_width adds a max-width boundary |
| 39 | pub struct ImageBuilder { |
| 40 | fit_height: Option<u32>, |
| 41 | fit_width: Option<u32>, |
| 42 | svg_builder: SvgBuilder, |
| 43 | } |
| 44 | |
| 45 | /// Error when converting to image |
| 46 | #[derive(Debug)] |
| 47 | pub enum ImageError { |
| 48 | /// Error while writing to file |
| 49 | IoError(io::Error), |
| 50 | /// Error while creating image |
| 51 | ImageError(String), |
| 52 | /// Error while convert to bytes |
| 53 | EncodingError(String), |
| 54 | } |
| 55 | |
| 56 | impl std::error::Error for ImageError {} |
| 57 | |
| 58 | impl std::fmt::Display for ImageError { |
| 59 | fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { |
| 60 | match self { |
| 61 | ImageError::IoError(io_err) => f.write_str(io_err.to_string().as_str()), |
| 62 | ImageError::ImageError(error) => f.write_str(error.as_str()), |
| 63 | ImageError::EncodingError(error) => f.write_str(error.as_str()), |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | /// Creates an ImageBuilder instance, which contains an [`SvgBuilder`] |
| 69 | impl Default for ImageBuilder { |
| 70 | fn default() -> Self { |
| 71 | ImageBuilder { |
| 72 | fit_height: None, |
| 73 | fit_width: None, |
| 74 | svg_builder: Default::default(), |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | impl Builder for ImageBuilder { |
| 80 | fn margin(&mut self, margin: usize) -> &mut Self { |
| 81 | self.svg_builder.margin(margin); |
| 82 | self |
| 83 | } |
| 84 | |
| 85 | fn module_color<C: Into<Color>>(&mut self, module_color: C) -> &mut Self { |
| 86 | self.svg_builder.module_color(module_color); |
| 87 | self |
| 88 | } |
| 89 | |
| 90 | fn background_color<C: Into<Color>>(&mut self, background_color: C) -> &mut Self { |
| 91 | self.svg_builder.background_color(background_color); |
| 92 | self |
| 93 | } |
| 94 | |
| 95 | fn shape(&mut self, shape: Shape) -> &mut Self { |
| 96 | self.svg_builder.shape(shape); |
| 97 | self |
| 98 | } |
| 99 | |
| 100 | fn image(&mut self, image: String) -> &mut Self { |
| 101 | self.svg_builder.image(image); |
| 102 | self |
| 103 | } |
| 104 | |
| 105 | fn image_background_color<C: Into<Color>>(&mut self, image_background_color: C) -> &mut Self { |
| 106 | self.svg_builder |
| 107 | .image_background_color(image_background_color); |
| 108 | self |
| 109 | } |
| 110 | |
| 111 | fn image_background_shape( |
| 112 | &mut self, |
| 113 | image_background_shape: super::ImageBackgroundShape, |
| 114 | ) -> &mut Self { |
| 115 | self.svg_builder |
| 116 | .image_background_shape(image_background_shape); |
| 117 | self |
| 118 | } |
| 119 | |
| 120 | fn image_size(&mut self, image_size: f64) -> &mut Self { |
| 121 | self.svg_builder.image_size(image_size); |
| 122 | self |
| 123 | } |
| 124 | |
| 125 | fn image_gap(&mut self, gap: f64) -> &mut Self { |
| 126 | self.svg_builder.image_gap(gap); |
| 127 | self |
| 128 | } |
| 129 | |
| 130 | fn image_position(&mut self, x: f64, y: f64) -> &mut Self { |
| 131 | self.svg_builder.image_position(x, y); |
| 132 | self |
| 133 | } |
| 134 | |
| 135 | fn shape_color<C: Into<Color>>(&mut self, shape: Shape, color: C) -> &mut Self { |
| 136 | self.svg_builder.shape_color(shape, color); |
| 137 | self |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | impl ImageBuilder { |
| 142 | /// Add a max-height boundary |
| 143 | pub fn fit_height(&mut self, height: u32) -> &mut Self { |
| 144 | self.fit_height = Some(height); |
| 145 | self |
| 146 | } |
| 147 | |
| 148 | /// Add a max-width boundary |
| 149 | pub fn fit_width(&mut self, width: u32) -> &mut Self { |
| 150 | self.fit_width = Some(width); |
| 151 | self |
| 152 | } |
| 153 | |
| 154 | // From https://github.com/RazrFalcon/resvg/blob/374a25f/crates/resvg/tests/integration/main.rs |
| 155 | /// Return a pixmap containing the svg for a QRCode |
| 156 | pub fn to_pixmap(&self, qr: &QRCode) -> Pixmap { |
| 157 | let opt = usvg::Options::default(); |
| 158 | |
| 159 | let tree = { |
| 160 | let svg_data = self.svg_builder.to_str(qr); |
| 161 | let tree = usvg::Tree::from_str(&svg_data, &opt); |
| 162 | tree.expect("Failed to parse SVG") |
| 163 | }; |
| 164 | |
| 165 | let (width, height, transform) = self.fit(tree.size()); |
| 166 | let mut pixmap = tiny_skia::Pixmap::new(width, height).expect("Failed to create pixmap"); |
| 167 | |
| 168 | resvg::render(&tree, transform, &mut pixmap.as_mut()); |
| 169 | |
| 170 | pixmap |
| 171 | } |
| 172 | |
| 173 | /// Saves the image for a QRCode to a file |
| 174 | pub fn to_file(&self, qr: &QRCode, file: &str) -> Result<(), ImageError> { |
| 175 | use io::{Error, ErrorKind}; |
| 176 | |
| 177 | self.to_pixmap(qr) |
| 178 | .save_png(file) |
| 179 | .map_err(|err| ImageError::IoError(Error::new(ErrorKind::Other, err.to_string()))) |
| 180 | } |
| 181 | |
| 182 | /// Saves the image for a QRCode in a byte buffer |
| 183 | pub fn to_bytes(&self, qr: &QRCode) -> Result<Vec<u8>, ImageError> { |
| 184 | let out = self.to_pixmap(qr); |
| 185 | out.encode_png() |
| 186 | .map_err(|err| ImageError::EncodingError(err.to_string())) |
| 187 | } |
| 188 | |
| 189 | fn fit(&self, tree_size: Size) -> (u32, u32, Transform) { |
| 190 | let factor = match (self.fit_width, self.fit_height) { |
| 191 | // Get the scaling factor by checking which dimensions can be scaled up the least |
| 192 | (Some(width), Some(height)) => { |
| 193 | (width as f32 / tree_size.width()).min(height as f32 / tree_size.height()) |
| 194 | } |
| 195 | (Some(width), None) => width as f32 / tree_size.width(), |
| 196 | (None, Some(height)) => height as f32 / tree_size.height(), |
| 197 | (None, None) => 1f32, |
| 198 | }; |
| 199 | |
| 200 | ( |
| 201 | (tree_size.width() * factor) as u32, |
| 202 | (tree_size.height() * factor) as u32, |
| 203 | tiny_skia::Transform::from_scale(factor, factor), |
| 204 | ) |
| 205 | } |
| 206 | } |