Rust QR碼函式庫

使用 Rust 產生 QR碼

Rust 的 qrcode crate 提供快速、記憶體安全的 QR碼產生。非常適合高效能應用、WebAssembly 和系統級工具。

安裝

將 qrcode crate 新增到您的 Cargo.toml。

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

使用 Rust 產生 QR碼

使用 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 中產生 QR碼

使用 reqwest 從 Rust 呼叫 QRCode.fun API 產生樣式化 QR碼。

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(())
}

即時 QR碼預覽

立即嘗試使用 Rust 產生 QR碼。

QR碼預覽

原生函式庫 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 QR碼使用情境

Rust 應用中 QR碼的常見情境。

WebAssembly

將 QR碼產生編譯為 WASM,在瀏覽器端實現極快的 QR碼建立,無需 JavaScript 函式庫。

CLI 工具

建構命令列工具,產生 QR碼用於終端機顯示、檔案輸出或剪貼簿整合。

高效能伺服器

在 Actix 或 Axum Web 伺服器中產生 QR碼,實現最小記憶體配置和最大吞吐量。

嵌入式系統

在資源受限的裝置上執行 QR碼產生,充分發揮 Rust 零成本抽象的優勢。

常見問題

關於使用 Rust 產生 QR碼的常見問題。

qrcode crate 是最受歡迎的選擇。它將 QR碼產生為 SVG 字串或矩陣,您可以使用 image crate 進行渲染。

開始使用 Rust 產生 QR碼

使用我們的免費產生器或將 API 整合到您的 Rust 應用中。