qrcode-rs 0.3.0

QR code encoder in Rust,Generate QR Code matrices and images in RAW, PNG and SVG formats.
Documentation
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
#![cfg(feature = "image")]
use crate::render::{Canvas, Pixel};
use crate::types::Color;

use image::{DynamicImage, GenericImageView, ImageBuffer, Luma, LumaA, Primitive, Rgb, Rgba};

macro_rules! impl_pixel_for_image_pixel {
    ($p:ident<$s:ident>: $c:pat => $d:expr) => {
        impl<$s> Pixel for $p<$s>
        where
            $s: Primitive + 'static,
            $p<$s>: image::Pixel<Subpixel = $s>,
        {
            type Image = ImageBuffer<Self, Vec<$s>>;
            type Canvas = (Self, Self::Image);

            fn default_color(color: Color) -> Self {
                match color.select($s::zero(), $s::max_value()) {
                    $c => $p($d),
                }
            }
        }
    };
}

impl_pixel_for_image_pixel! { Luma<S>: p => [p] }
impl_pixel_for_image_pixel! { LumaA<S>: p => [p, S::max_value()] }
impl_pixel_for_image_pixel! { Rgb<S>: p => [p, p, p] }
impl_pixel_for_image_pixel! { Rgba<S>: p => [p, p, p, S::max_value()] }

impl<P: image::Pixel + 'static> Canvas for (P, ImageBuffer<P, Vec<P::Subpixel>>) {
    type Pixel = P;
    type Image = ImageBuffer<P, Vec<P::Subpixel>>;

    fn new(width: u32, height: u32, dark_pixel: P, light_pixel: P) -> Self {
        (dark_pixel, ImageBuffer::from_pixel(width, height, light_pixel))
    }

    fn draw_dark_pixel(&mut self, x: u32, y: u32) {
        self.1.put_pixel(x, y, self.0);
    }

    fn into_image(self) -> ImageBuffer<P, Vec<P::Subpixel>> {
        self.1
    }
}

/// Overlays a logo onto the center of a QR code image.
///
/// The logo is automatically resized to fit within the specified ratio of the
/// QR code's dimensions. A white padding margin is added around the logo to
/// ensure scannability.
///
/// Use `image::DynamicImage::from(qr_image)` to convert an `ImageBuffer` to
/// `DynamicImage` if needed.
///
/// # Arguments
///
/// * `qr_image` - The rendered QR code as a `DynamicImage`.
/// * `logo` - The logo image to overlay (any format the `image` crate supports).
/// * `size_ratio` - Maximum logo size as a fraction of the QR code size (0.0–0.5).
///   Recommended: 0.2–0.3. Values above 0.35 may make the QR code unscannable.
///
/// # Example
///
/// ```no_run
/// use qrcode_rs::QrCode;
/// use qrcode_rs::render::image::overlay_logo;
/// use image::{Rgb, DynamicImage, open};
///
/// let code = QrCode::with_error_correction_level(b"https://example.com", qrcode_rs::EcLevel::H).unwrap();
/// let qr = DynamicImage::ImageRgb8(code.render::<Rgb<u8>>().min_dimensions(300, 300).build());
/// let logo = open("logo.png").unwrap();
/// let final_image = overlay_logo(&qr, &logo, 0.25);
/// final_image.save("qr_with_logo.png").unwrap();
/// ```
pub fn overlay_logo(qr_image: &DynamicImage, logo: &DynamicImage, size_ratio: f32) -> DynamicImage {
    let (qr_w, qr_h) = qr_image.dimensions();
    let ratio = size_ratio.clamp(0.05, 0.5);

    // Convert QR image to RGBA8 for compositing.
    let mut result = qr_image.to_rgba8();

    // Calculate target logo size (with padding margin).
    let max_logo_dim = ((qr_w.min(qr_h) as f32 * ratio) as u32).max(1);
    let padding = (max_logo_dim as f32 * 0.1) as u32;
    let logo_target = max_logo_dim.saturating_sub(2 * padding).max(1);

    // Resize logo preserving aspect ratio.
    let logo_resized = logo.resize(logo_target, logo_target, image::imageops::FilterType::Lanczos3);
    let (lw, lh) = logo_resized.dimensions();

    // Center position.
    let x_off = (qr_w.saturating_sub(lw)) / 2;
    let y_off = (qr_h.saturating_sub(lh)) / 2;

    // Draw white background behind the logo area.
    let bg_x = x_off.saturating_sub(padding);
    let bg_y = y_off.saturating_sub(padding);
    let bg_w = (lw + 2 * padding).min(qr_w - bg_x);
    let bg_h = (lh + 2 * padding).min(qr_h - bg_y);
    let white = Rgba([255u8, 255, 255, 255]);
    for py in bg_y..bg_y + bg_h {
        for px in bg_x..bg_x + bg_w {
            result.put_pixel(px, py, white);
        }
    }

    // Composite logo onto the QR code with alpha blending.
    let logo_rgba = logo_resized.to_rgba8();
    for py in 0..lh {
        for px in 0..lw {
            let src = logo_rgba.get_pixel(px, py);
            let [sr, sg, sb, sa] = src.0;
            if sa == 0 {
                continue;
            }
            let dst = *result.get_pixel(x_off + px, y_off + py);
            let [dr, dg, db, _da] = dst.0;
            let af = sa as f32 / 255.0;
            let inv = 1.0 - af;
            let r = (dr as f32 * inv + sr as f32 * af) as u8;
            let g = (dg as f32 * inv + sg as f32 * af) as u8;
            let b = (db as f32 * inv + sb as f32 * af) as u8;
            result.put_pixel(x_off + px, y_off + py, Rgba([r, g, b, 255]));
        }
    }

    DynamicImage::ImageRgba8(result)
}

/// Re-exports the `image` crate's `ImageFormat` for convenience.
pub use image::ImageFormat;

/// Encodes a QR code image into the specified format and writes to a byte vector.
///
/// This is a convenience wrapper around the `image` crate's format support.
/// Supported formats depend on the `image` crate's enabled features
/// (default: PNG, JPEG, GIF, BMP, TIFF, WebP).
///
/// # Example
///
/// ```no_run
/// use qrcode_rs::QrCode;
/// use qrcode_rs::render::image::{encode_to_format, ImageFormat};
/// use image::{DynamicImage, Rgb};
///
/// let code = QrCode::new(b"Hello").unwrap();
/// let img = DynamicImage::ImageRgb8(code.render::<Rgb<u8>>().min_dimensions(200, 200).build());
/// let jpeg_bytes = encode_to_format(&img, ImageFormat::Jpeg).unwrap();
/// std::fs::write("qr.jpg", &jpeg_bytes).unwrap();
/// ```
pub fn encode_to_format(image: &DynamicImage, format: ImageFormat) -> image::ImageResult<Vec<u8>> {
    let mut buf = std::io::Cursor::new(Vec::new());
    image.write_to(&mut buf, format)?;
    Ok(buf.into_inner())
}

/// Direction of a gradient sweep.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum GradientDirection {
    /// Top to bottom.
    Vertical,
    /// Left to right.
    Horizontal,
    /// Top-left to bottom-right.
    Diagonal,
}

/// A linear gradient defined by two endpoint colors.
#[derive(Copy, Clone, Debug)]
pub struct Gradient {
    pub direction: GradientDirection,
    pub start_color: Rgba<u8>,
    pub end_color: Rgba<u8>,
}

/// Applies a gradient tint to the light (background) pixels of a QR code image.
///
/// Dark (foreground) pixels are preserved. Light pixels are replaced with the
/// interpolated gradient color based on their position.
///
/// # Example
///
/// ```no_run
/// use qrcode_rs::QrCode;
/// use qrcode_rs::render::image::{apply_gradient_background, Gradient, GradientDirection};
/// use image::{Rgb, DynamicImage, Rgba};
///
/// let code = QrCode::new(b"Hello").unwrap();
/// let qr = DynamicImage::ImageRgb8(code.render::<Rgb<u8>>().min_dimensions(200, 200).build());
/// let gradient = Gradient {
///     direction: GradientDirection::Vertical,
///     start_color: Rgba([255, 200, 200, 255]),
///     end_color: Rgba([200, 200, 255, 255]),
/// };
/// let result = apply_gradient_background(&qr, &gradient);
/// result.save("qr_gradient.png").unwrap();
/// ```
pub fn apply_gradient_background(image: &DynamicImage, gradient: &Gradient) -> DynamicImage {
    let rgba = image.to_rgba8();
    let (w, h) = rgba.dimensions();
    let mut result = rgba.clone();

    let sc = gradient.start_color.0;
    let ec = gradient.end_color.0;

    for y in 0..h {
        for x in 0..w {
            let pixel = *rgba.get_pixel(x, y);
            let [r, g, b, a] = pixel.0;

            // Detect light pixels: high luminance and not fully transparent.
            let lum = (r as u32 + g as u32 + b as u32) / 3;
            if lum > 200 && a > 0 {
                let t = match gradient.direction {
                    GradientDirection::Vertical => {
                        if h <= 1 {
                            0.0
                        } else {
                            y as f32 / (h - 1) as f32
                        }
                    }
                    GradientDirection::Horizontal => {
                        if w <= 1 {
                            0.0
                        } else {
                            x as f32 / (w - 1) as f32
                        }
                    }
                    GradientDirection::Diagonal => {
                        if w <= 1 || h <= 1 {
                            0.0
                        } else {
                            (x as f32 / (w - 1) as f32 + y as f32 / (h - 1) as f32) / 2.0
                        }
                    }
                };
                let inv = 1.0 - t;
                let nr = (sc[0] as f32 * inv + ec[0] as f32 * t) as u8;
                let ng = (sc[1] as f32 * inv + ec[1] as f32 * t) as u8;
                let nb = (sc[2] as f32 * inv + ec[2] as f32 * t) as u8;
                let na = (sc[3] as f32 * inv + ec[3] as f32 * t) as u8;
                result.put_pixel(x, y, Rgba([nr, ng, nb, na]));
            }
        }
    }

    DynamicImage::ImageRgba8(result)
}

#[cfg(test)]
mod render_tests {
    use crate::render::Renderer;
    use crate::types::Color;
    use image::{GenericImageView, ImageBuffer, Luma, Rgba};

    #[test]
    fn test_render_luma8_unsized() {
        let image = Renderer::<Luma<u8>>::new(
            &[
                Color::Light,
                Color::Dark,
                Color::Dark,
                //
                Color::Dark,
                Color::Light,
                Color::Light,
                //
                Color::Light,
                Color::Dark,
                Color::Light,
            ],
            3,
            1,
        )
        .module_dimensions(1, 1)
        .build();

        #[rustfmt::skip]
            let expected = [
            255, 255, 255, 255, 255,
            255, 255,   0,   0, 255,
            255,   0, 255, 255, 255,
            255, 255,   0, 255, 255,
            255, 255, 255, 255, 255,
        ];
        assert_eq!(image.into_raw(), expected);
    }

    #[test]
    fn test_render_rgba_unsized() {
        let image = Renderer::<Rgba<u8>>::new(&[Color::Light, Color::Dark, Color::Dark, Color::Dark], 2, 1)
            .module_dimensions(1, 1)
            .build();

        #[rustfmt::skip]
            let expected: &[u8] = &[
            255,255,255,255, 255,255,255,255, 255,255,255,255, 255,255,255,255,
            255,255,255,255, 255,255,255,255,   0,  0,  0,255, 255,255,255,255,
            255,255,255,255,   0,  0,  0,255,   0,  0,  0,255, 255,255,255,255,
            255,255,255,255, 255,255,255,255, 255,255,255,255, 255,255,255,255,
        ];

        assert_eq!(image.into_raw(), expected);
    }

    #[test]
    fn test_render_resized_min() {
        let image = Renderer::<Luma<u8>>::new(&[Color::Dark, Color::Light, Color::Light, Color::Dark], 2, 1)
            .min_dimensions(10, 10)
            .build();

        #[rustfmt::skip]
            let expected: &[u8] = &[
            255,255,255, 255,255,255, 255,255,255, 255,255,255,
            255,255,255, 255,255,255, 255,255,255, 255,255,255,
            255,255,255, 255,255,255, 255,255,255, 255,255,255,

            255,255,255,   0,  0,  0, 255,255,255, 255,255,255,
            255,255,255,   0,  0,  0, 255,255,255, 255,255,255,
            255,255,255,   0,  0,  0, 255,255,255, 255,255,255,

            255,255,255, 255,255,255,   0,  0,  0, 255,255,255,
            255,255,255, 255,255,255,   0,  0,  0, 255,255,255,
            255,255,255, 255,255,255,   0,  0,  0, 255,255,255,

            255,255,255, 255,255,255, 255,255,255, 255,255,255,
            255,255,255, 255,255,255, 255,255,255, 255,255,255,
            255,255,255, 255,255,255, 255,255,255, 255,255,255,
        ];

        assert_eq!(image.dimensions(), (12, 12));
        assert_eq!(image.into_raw(), expected);
    }

    #[test]
    fn test_render_resized_max() {
        let image = Renderer::<Luma<u8>>::new(&[Color::Dark, Color::Light, Color::Light, Color::Dark], 2, 1)
            .max_dimensions(10, 5)
            .build();

        #[rustfmt::skip]
            let expected: &[u8] = &[
            255,255, 255,255, 255,255, 255,255,

            255,255,   0,  0, 255,255, 255,255,

            255,255, 255,255,   0,  0, 255,255,

            255,255, 255,255, 255,255, 255,255,
        ];

        assert_eq!(image.dimensions(), (8, 4));
        assert_eq!(image.into_raw(), expected);
    }

    #[test]
    fn test_overlay_logo() {
        use super::overlay_logo;
        use image::DynamicImage;

        // Create a small QR code image.
        let qr = Renderer::<Rgba<u8>>::new(&[Color::Dark, Color::Light, Color::Light, Color::Dark], 2, 0)
            .module_dimensions(10, 10)
            .build();
        let qr_dyn = DynamicImage::ImageRgba8(qr);

        // Create a small red logo.
        let logo = DynamicImage::ImageRgba8(ImageBuffer::from_pixel(4, 4, Rgba([255u8, 0, 0, 255])));

        let result = overlay_logo(&qr_dyn, &logo, 0.5);
        assert_eq!(result.dimensions(), (20, 20));

        // The center pixels should be the logo (red).
        let center = result.as_rgba8().unwrap().get_pixel(10, 10);
        assert_eq!(center.0[0], 255); // red channel
        assert_eq!(center.0[3], 255); // alpha
    }

    #[test]
    fn test_overlay_logo_small_ratio() {
        use super::overlay_logo;
        use image::DynamicImage;

        let qr = Renderer::<Rgba<u8>>::new(&[Color::Dark, Color::Light, Color::Light, Color::Dark], 2, 0)
            .module_dimensions(100, 100)
            .build();
        let qr_dyn = DynamicImage::ImageRgba8(qr);
        let logo = DynamicImage::ImageRgba8(ImageBuffer::from_pixel(4, 4, Rgba([0u8, 255, 0, 255])));

        let result = overlay_logo(&qr_dyn, &logo, 0.2);
        assert_eq!(result.dimensions(), (200, 200));
    }

    #[test]
    fn test_encode_to_format_png() {
        use super::{ImageFormat, encode_to_format};
        use image::DynamicImage;

        let img = Renderer::<Rgba<u8>>::new(&[Color::Dark, Color::Light, Color::Light, Color::Dark], 2, 0)
            .module_dimensions(10, 10)
            .build();
        let dyn_img = DynamicImage::ImageRgba8(img);
        let png_bytes = encode_to_format(&dyn_img, ImageFormat::Png).unwrap();
        assert!(!png_bytes.is_empty());
        // PNG magic bytes
        assert_eq!(&png_bytes[..8], &[137, 80, 78, 71, 13, 10, 26, 10]);
    }

    #[test]
    fn test_encode_to_format_jpeg() {
        use super::{ImageFormat, encode_to_format};
        use image::DynamicImage;

        let img = Renderer::<Rgba<u8>>::new(&[Color::Dark, Color::Light, Color::Light, Color::Dark], 2, 0)
            .module_dimensions(10, 10)
            .build();
        let dyn_img = DynamicImage::ImageRgba8(img);
        let jpeg_bytes = encode_to_format(&dyn_img, ImageFormat::Jpeg).unwrap();
        assert!(!jpeg_bytes.is_empty());
        // JPEG magic bytes (FF D8 FF)
        assert_eq!(&jpeg_bytes[..3], &[0xFF, 0xD8, 0xFF]);
    }

    #[test]
    fn test_for_web() {
        let img =
            Renderer::<Luma<u8>>::new(&[Color::Dark, Color::Light, Color::Light, Color::Dark], 2, 1).for_web().build();
        // for_web sets min_dimensions(200, 200). With modules_count=2 + quiet_zone=2*4=8,
        // total modules = 10. Unit = 200/10 = 20. Image = 10*20 = 200.
        assert!(img.dimensions().0 >= 200);
        assert!(img.dimensions().1 >= 200);
    }

    #[test]
    fn test_for_print_300() {
        let img = Renderer::<Luma<u8>>::new(&[Color::Dark, Color::Light, Color::Light, Color::Dark], 2, 1)
            .for_print(300)
            .build();
        assert!(img.dimensions().0 >= 300);
        assert!(img.dimensions().1 >= 300);
    }

    #[test]
    fn test_for_social_twitter() {
        let img = Renderer::<Luma<u8>>::new(&[Color::Dark, Color::Light, Color::Light, Color::Dark], 2, 1)
            .for_social("twitter")
            .build();
        assert!(img.dimensions().0 >= 400);
    }

    #[test]
    fn test_for_social_instagram() {
        let img = Renderer::<Luma<u8>>::new(&[Color::Dark, Color::Light, Color::Light, Color::Dark], 2, 1)
            .for_social("instagram")
            .build();
        assert!(img.dimensions().0 >= 1080);
    }

    #[test]
    fn test_gradient_vertical() {
        use super::{Gradient, GradientDirection, apply_gradient_background};
        use image::DynamicImage;

        let qr = Renderer::<Rgba<u8>>::new(&[Color::Dark, Color::Light, Color::Light, Color::Dark], 2, 0)
            .module_dimensions(10, 10)
            .build();
        let qr_dyn = DynamicImage::ImageRgba8(qr);
        let gradient = Gradient {
            direction: GradientDirection::Vertical,
            start_color: Rgba([255, 0, 0, 255]),
            end_color: Rgba([0, 0, 255, 255]),
        };
        let result = apply_gradient_background(&qr_dyn, &gradient);
        assert_eq!(result.dimensions(), (20, 20));
        // Dark pixels should be preserved (black).
        let dark = result.as_rgba8().unwrap().get_pixel(0, 0);
        assert_eq!(dark.0[0], 0);
        assert_eq!(dark.0[1], 0);
        assert_eq!(dark.0[2], 0);
    }

    #[test]
    fn test_gradient_horizontal() {
        use super::{Gradient, GradientDirection, apply_gradient_background};
        use image::DynamicImage;

        let qr = Renderer::<Rgba<u8>>::new(&[Color::Dark, Color::Light, Color::Light, Color::Dark], 2, 0)
            .module_dimensions(10, 10)
            .build();
        let qr_dyn = DynamicImage::ImageRgba8(qr);
        let gradient = Gradient {
            direction: GradientDirection::Horizontal,
            start_color: Rgba([255, 0, 0, 255]),
            end_color: Rgba([0, 0, 255, 255]),
        };
        let result = apply_gradient_background(&qr_dyn, &gradient);
        assert_eq!(result.dimensions(), (20, 20));
    }

    #[test]
    fn test_gradient_diagonal() {
        use super::{Gradient, GradientDirection, apply_gradient_background};
        use image::DynamicImage;

        let qr = Renderer::<Rgba<u8>>::new(&[Color::Dark, Color::Light, Color::Light, Color::Dark], 2, 0)
            .module_dimensions(10, 10)
            .build();
        let qr_dyn = DynamicImage::ImageRgba8(qr);
        let gradient = Gradient {
            direction: GradientDirection::Diagonal,
            start_color: Rgba([255, 255, 0, 255]),
            end_color: Rgba([0, 255, 255, 255]),
        };
        let result = apply_gradient_background(&qr_dyn, &gradient);
        assert_eq!(result.dimensions(), (20, 20));
    }
}