基于 ZXing.Net 库生成二维码,支持自定义尺寸和保存路径。
using ZXing; using ZXing.QrCode; using ZXing.QrCode.Internal; public class QrCodeGenerator { // 生成二维码并保存为图片 public static bool GenerateQrCode(string content, string outputPath, int width = 300, int height = 300) { try { var writer = new BarcodeWriterPixelData { Format = BarcodeFormat.QR_CODE, Options = new QrCodeEncodingOptions { Width = width, Height = height, Margin = 1, ErrorCorrection = ErrorCorrectionLevel.H } }; var pixelData = writer.Write(content); using (var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height)) using (var ms = new System.IO.MemoryStream()) { var bitmapData = bitmap.LockBits(/* 省略锁定参数 */); try { /* 写入像素数据 */ } finally { bitmap.UnlockBits(bitmapData); } bitmap.Save(outputPath, System.Drawing.Imaging.ImageFormat.Png); } Console.WriteLine("二维码生成成功!"); return true; } catch (Exception ex) { Console.WriteLine($"生成失败: {ex.Message}"); return false; } } // 调用示例 public static void TestQrGenerate() { GenerateQrCode("https://www.example.com", "qrcode.png", 300, 300); } }
注意:需安装 ZXing.Net NuGet 包。