zoukankan      html  css  js  c++  java
  • WPF-生成二维码(条码)

    1.效果图

    2.BarcodeWriter 用于生成图片格式的条码类,通过Write函数进行输出。

    BarcodeFormat 枚举类型,条码格式。

    EncodingOptions,主要设置宽,高,编码方式等信息。

    BitMatrix 表示按位表示的二维矩阵数组,元素的值用true和false表示二进制中的1和0。

    / 生成二维码
            private System.Drawing.Image GeneratorQR(string msg)
            {
    
                var QRmsg = "https://www.baidu.com/";
                if (!Directory.Exists(System.AppDomain.CurrentDomain.BaseDirectory + "QRBar1\"))
                {
                    Directory.CreateDirectory(System.AppDomain.CurrentDomain.BaseDirectory + "QRBar1\");
    
                }
                var QRpath = System.AppDomain.CurrentDomain.BaseDirectory + "QRBar1\" +
                                       "QrCode" + ".jpg";
                // MessageBox.Show(QRpath);
    
                BarcodeWriter writer = new BarcodeWriter
                {
                    Format = BarcodeFormat.QR_CODE
                };
                writer.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");     // 编码问题
                writer.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);
                int codeSizeInPixels = 150;      // 设置图片长宽
                writer.Options.Height = 150;
                writer.Options.Width = 150;
                writer.Options.Margin = 0;       // 设置边框
                BitMatrix bm = writer.Encode(msg);
                Bitmap img = writer.Write(bm);
                img.Save(@QRpath);
                imageQR.Source = BitmapToBitmapImage(img);
                return img;
            }

    3.

    Bitmap 转换为 BitmapImage(避免图片被占用,我之前的博客有提到过)
     // Bitmap --> BitmapImage
            public static BitmapImage BitmapToBitmapImage(Bitmap bitmap)
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    bitmap.Save(stream, ImageFormat.Png);
                    stream.Position = 0;
                    BitmapImage result = new BitmapImage();
                    result.BeginInit();
                    result.CacheOption = BitmapCacheOption.OnLoad;
                    result.StreamSource = stream;
                    result.EndInit();
                    result.Freeze();
                    return result;
                }
            }

    4.源码下载。

     https://files-cdn.cnblogs.com/files/king10086/QR.7z

  • 相关阅读:
    实时需要分析
    .NET 单元测试的艺术&单元测试之道C#版
    代码演示C#各2.0到8.0版本[FK,2.0-4.8.0]
    微软Visual Studio Code 0.8.0发布,新增多种主题
    ASP.NET 5 Beta 7 版本
    软件开发设计原则
    Immutable(不可变)集合
    使用Hystrix提高系统可用性
    微软发布 Windows Server 2016 预览版第三版,开发者要重点关注Nano Server
    Akka.NET v1.0 已发布,支持Mono
  • 原文地址:https://www.cnblogs.com/king10086/p/12653402.html
Copyright © 2011-2022 走看看