WPF调用zxing生成二维码

1.登录http://zxingnet.codeplex.com/,下载对应.net版本的zxing库

2.引入zxing.dll

3.新建界面控件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ZXing.Common;
using ZXing;
using ZXing.QrCode;
using System.Runtime.InteropServices;
using System.Drawing;

namespace zxingQRCodeDemo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        // 注销对象方法API
        [DllImport("gdi32")]
        static extern int DeleteObject(IntPtr o);
        public MainWindow()
        {
            InitializeComponent();
        }

        /// <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 ip = bitmap.GetHbitmap();//从GDI+ Bitmap创建GDI位图对象
                                            //Imaging.CreateBitmapSourceFromHBitmap方法,基于所提供的非托管位图和调色板信息的指针,返回一个托管的BitmapSource
            BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, IntPtr.Zero, Int32Rect.Empty,
            System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
            DeleteObject(ip);
            return bitmapSource;
        }

        private void btnMake_Click(object sender, RoutedEventArgs e)
        {
            imQRCode.Source = createQRCode("牛逼不牛逼", 250, 250);
        }
    }
}

 注意,二维码是有容量的,最多635个汉字;2685个字符。

posted @ 2017-08-25 19:21  卖雨伞的小男孩  阅读(664)  评论(0编辑  收藏  举报