C# 生成二维码(带Logo)
第一种方式
我们需要引用 ThoughtWorks.QRCode.dll 生成带logo二维码(framework4.0以上)
下载地址:https://pan.baidu.com/s/1mBjd7PHB-Klybx18Z5Og8A
提取码: ugwa
/// <summary> /// 创建二维码 /// </summary> /// <param name="content">内容</param> /// <returns></returns> public static Bitmap CreateQRCode(string content) { try { QRCodeEncoder qrEncoder = new QRCodeEncoder(); //二维码类型 qrEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE; //二维码尺寸 qrEncoder.QRCodeScale = 4; //二维码版本 qrEncoder.QRCodeVersion = 7; //二维码容错程度 qrEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M; //字体与背景颜色 qrEncoder.QRCodeBackgroundColor = Color.White; qrEncoder.QRCodeForegroundColor = Color.Black; //UTF-8编码类型 Bitmap qrcode = qrEncoder.Encode(content, Encoding.UTF8); return qrcode; } catch (Exception) { return null; } }
/// <summary> /// 生成带logo二维码 /// </summary> /// <returns></returns> public static Bitmap CreateQRCodeWithLogo(string content, string logopath) { //生成二维码 Bitmap qrcode = CreateQRCode(content); //生成logo Bitmap logo = new Bitmap(logopath); //合成 ImageUtility util = new ImageUtility(); Bitmap finalImage = util.MergeQrImg(qrcode, logo); return finalImage; }
/// <summary> /// 保存二维码 /// </summary> /// <param name="QRCode">二维码图片</param> /// <param name="SavePath">保存路径</param> /// <param name="QRCodeName">图片名称</param> public static void SaveQRCode(Bitmap QRCode, string SavePath, string QRCodeName) { if (!Directory.Exists(SavePath)) { Directory.CreateDirectory(SavePath); } QRCode.Save(Path.Combine(SavePath, QRCodeName + ".png"), ImageFormat.Png); QRCode.Dispose(); }
第二种方式
我们需要引用 Gma.QrCodeNet.Encoding.Net45.dll (framework4.5以上)支持中文
下载地址:https://pan.baidu.com/s/1TKMwdWHYhTp_fJnTYHKnsQ
提取码: eqjh
// <summary> /// 生成保存二维码(framework4.5以上) /// </summary> /// <param name="CodeString"></param> /// <param name="PicName"></param> /// <param name="FilePath"></param> public static void CreateQRCode(string CodeString, string PicName, string FilePath) { QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode code = new QrCode(); qrEncoder.TryEncode(CodeString, out code); const int modelSizeInPixels = 4; GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(modelSizeInPixels, QuietZoneModules.Two) , Brushes.Black, Brushes.White); if (!Directory.Exists(FilePath)) { Directory.CreateDirectory(FilePath); } string filename = FilePath + "\\" + PicName + ".png"; using (FileStream stream = new FileStream(filename, FileMode.Create)) { render.WriteToStream(code.Matrix, ImageFormat.Png, stream); } }