WPF生成二维码

1、通过NuGet安装控件:

Install-Package ZXing.Net

2、添加引用System.Drawing

3、在xaml中添加一个Image控件,用于显示二维码,命名为image1

完整示例代码:

using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using ZXing;
using ZXing.Common;
using ZXing.QrCode;

namespace WpfDemo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        [DllImport("gdi32")]
        static extern int DeleteObject(IntPtr o);

        public MainWindow()
        {
            InitializeComponent();

            image1.Source = createQRCode("http://www.cnsos.net/", 1000, 1000);
        }

        /// <summary>
        /// 创建二维码图片
        /// </summary>
        /// <param name="content"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <returns></returns>
        private ImageSource createQRCode(string content, int width, int height)
        {
            EncodingOptions options;
            //包含一些编码、大小等的设置
            //BarcodeWriter :一个智能类来编码一些内容的条形码图像
            BarcodeWriter write = null;
            options = new QrCodeEncodingOptions
            {
                DisableECI = true,
                CharacterSet = "UTF-8",
                Width = width,
                Height = height,
                Margin = 0
            };
            write = new BarcodeWriter();
            //设置条形码格式
            write.Format = BarcodeFormat.QR_CODE;
            //获取或设置选项容器的编码和渲染过程。
            write.Options = options;
            //对指定的内容进行编码,并返回该条码的呈现实例。渲染属性渲染实例使用,必须设置方法调用之前。
            Bitmap bitmap = write.Write(content);
            IntPtr bmpHandle = bitmap.GetHbitmap();
            //从GDI+ Bitmap创建GDI位图对象
            //Imaging.CreateBitmapSourceFromHBitmap方法,基于所提供的非托管位图和调色板信息的指针,返回一个托管的BitmapSource
            BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bmpHandle, IntPtr.Zero, Int32Rect.Empty,
                                            BitmapSizeOptions.FromEmptyOptions());
            DeleteObject(bmpHandle);

            return bitmapSource;
        }
    }
}

 

转自:http://blog.csdn.net/wangshubo1989/article/details/47152533

posted @ 2017-09-13 16:32  wzwyc  阅读(1729)  评论(0编辑  收藏  举报