Rust 二维码库

使用 Rust 生成二维码

Rust 的 qrcode crate 提供快速、内存安全的二维码生成。非常适合高性能应用、WebAssembly 和系统级工具。

安装

将 qrcode crate 添加到您的 Cargo.toml。

Cargo.toml
[dependencies]
qrcode = "0.14"
image = "0.25"  # For PNG output

使用 Rust 生成二维码

使用 qrcode crate 的代码示例。

QR Code as SVG
use qrcode::QrCode;
use qrcode::render::svg;

fn main() {
    let code = QrCode::new("https://qrcode.fun").unwrap();
    let svg = code.render::<svg::Color>()
        .min_dimensions(200, 200)
        .build();

    std::fs::write("qrcode.svg", &svg).unwrap();
    println!("SVG QR code saved!");
}
QR Code as PNG
use qrcode::QrCode;
use image::Luma;

fn main() {
    let code = QrCode::new("https://qrcode.fun").unwrap();
    let image = code.render::<Luma<u8>>()
        .dark_color(Luma([26u8]))
        .light_color(Luma([255u8]))
        .quiet_zone(true)
        .min_dimensions(300, 300)
        .build();

    image.save("qrcode.png").unwrap();
    println!("PNG QR code saved!");
}
QRCode.fun API

通过 API 在 Rust 中生成二维码

使用 reqwest 从 Rust 调用 QRCode.fun API 生成样式化二维码。

Rust API 集成
use reqwest;
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = reqwest::Client::new();
    let response = client
        .post("https://qrcode.fun/api/generate-qr-styled")
        .json(&json!({
            "data": "https://qrcode.fun",
            "width": 300,
            "height": 300,
            "type": "png",
            "margin": 10,
            "dotsOptions": { "color": "#1A2B3C", "type": "rounded" },
            "cornersSquareOptions": { "color": "#8564C3", "type": "extra-rounded" },
            "backgroundOptions": { "color": "#FFFFFF" }
        }))
        .send()
        .await?;

    let result: serde_json::Value = response.json().await?;
    println!("{}", &result["data"].as_str().unwrap()[..50]);
    Ok(())
}

实时二维码预览

立即尝试使用 Rust 生成二维码。

二维码预览

原生库 vs API

比较使用 qrcode crate 与 QRCode.fun API。

功能qrcode CrateQRCode.fun API
设置复杂度cargo add + image crate 用于 PNG通过 reqwest 发送单次 HTTP 请求
自定义通过 image crate 设置颜色完整样式:颜色、形状、徽标
离线支持需要互联网
维护cargo update始终保持最新
输出格式SVG, PNG(使用 image crate), 终端PNG, SVG

Rust 二维码使用场景

Rust 应用中二维码的常见场景。

WebAssembly

将二维码生成编译为 WASM,在浏览器端实现极快的二维码创建,无需 JavaScript 库。

CLI 工具

构建命令行工具,生成二维码用于终端显示、文件输出或剪贴板集成。

高性能服务器

在 Actix 或 Axum Web 服务器中生成二维码,实现最小内存分配和最大吞吐量。

嵌入式系统

在资源受限的设备上运行二维码生成,充分发挥 Rust 零成本抽象的优势。

常见问题

关于使用 Rust 生成二维码的常见问题。

qrcode crate 是最流行的选择。它将二维码生成为 SVG 字符串或矩阵,您可以使用 image crate 进行渲染。

开始使用 Rust 生成二维码

使用我们的免费生成器或将 API 集成到您的 Rust 应用中。