next_web_utils/qr_code/qr_code_util.rs
1use fast_qr::{
2 convert::{image::ImageBuilder, svg::SvgBuilder, Builder, Shape},
3 QRBuilder,
4};
5
6pub struct QrCodeUtil;
7
8impl QrCodeUtil {
9 /// 生成二维码的方法
10 /// Generates a QR code based on the provided content and type.
11 /// 内容:要编码为二维码的字符串数据 | Content: The string data to encode into the QR code.
12 /// 类型:指定生成的二维码格式(SVG 或 PNG) | Type: Specifies the format of the QR code (SVG or PNG).
13 /// 返回值:成功时返回 `QrCodeOutput`,失败时返回错误 | Returns: `QrCodeOutput` on success, error on failure.
14 /// 使用 `QRBuilder` 创建二维码对象 | Create a QR code object using `QRBuilder`.
15 pub fn generate_qr_code(
16 content: &str,
17 qr_code_type: QrCodeType,
18 ) -> Result<QrCodeOutput, Box<dyn std::error::Error>> {
19 let qrcode = QRBuilder::new(content).build()?;
20 // 根据指定的类型生成二维码输出
21 // Generate QR code output based on the specified type.
22 let output = match qr_code_type {
23 QrCodeType::Svg => {
24 let svg = SvgBuilder::default()
25 .shape(Shape::RoundedSquare)
26 .to_str(&qrcode);
27 QrCodeOutput::Svg(svg)
28 }
29 QrCodeType::Png(width, height) => {
30 // 使用默认的图像构建器 | Use the default image builder.
31 let png = ImageBuilder::default()
32 .shape(Shape::RoundedSquare)
33 .background_color([255, 255, 255, 0])
34 .fit_width(width)
35 .fit_height(height)
36 .to_bytes(&qrcode)?;
37 QrCodeOutput::Png(png)
38 }
39 };
40 // 返回生成的二维码输出 | Return the generated QR code output.
41 Ok(output)
42 }
43}
44
45/// 定义二维码的输出类型
46/// Defines the output format of the QR code.
47pub enum QrCodeOutput {
48 // SVG 格式的二维码,存储为字符串 | SVG format QR code, stored as a string.
49 Svg(String),
50 // PNG 格式的二维码,存储为字节数组 | PNG format QR code, stored as a byte array.
51 Png(Vec<u8>),
52}
53
54/// 定义二维码的生成类型
55/// Defines the type of QR code to generate.
56#[derive(Debug, Clone, Copy)]
57pub enum QrCodeType {
58 // 表示生成 SVG 格式的二维码 | Indicates generating an SVG format QR code.
59 Svg,
60 // 表示生成 PNG 格式的二维码,并指定宽度和高度 | Indicates generating a PNG format QR code with specified width and height.
61 Png(u32, u32),
62}