介绍:

如果需要实在WPF窗体程序中现类似如下的二维码图片生成功能,可以通过本文的方法实现

 

添加步骤:

1、在http://zxingnet.codeplex.com/站点上下载ZXing .Net的第三方库

2、下载后解压可以看到有针对不同.Net版本的dll文件,在你的工程中引用正确的dll

3、然后再你的工程中引用System.Drawing程序集

4、在你需要生成二维码的Window中,加入一下代码

 

// 注销对象方法API
[DllImport("gdi32")]
static extern int DeleteObject(IntPtr o);
/**
 * 创建二维码图片
 */
private ImageSource createQRCode(String content, int width, int height)
{
    EncodingOptions options;//包含一些编码、大小等的设置
    BarcodeWriter write = null;//用来生成二维码,对应的BarcodeReader用来解码
    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();
    BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
        ip, IntPtr.Zero, Int32Rect.Empty,
        System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
    DeleteObject(ip);
    return bitmapSource;
}

 

5、调用createQRCode即可完成二维码的ImageSource生成,然后使用Image即可显示

 

posted on 2014-11-06 09:43  HalfmanG2  阅读(2491)  评论(0编辑  收藏  举报