首页 > 其他 > 详细

【WPF】生成二维码

时间:2014-02-22 04:59:11      阅读:433      评论:0      收藏:0      [点我收藏+]

第一步,下载Google的ZXing类库,以便引用;

bubuko.com,布布扣
  BitMatrix bitMatrix;
    
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            string content = this.txtChat.Text;


                Dictionary<EncodeHintType, object> hints = new Dictionary<EncodeHintType, object>();
                hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
                
                bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 200, 200);
                this.img.Stretch = Stretch.Fill;
                this.img.Source = toImage(bitMatrix);
        }
bubuko.com,布布扣

下面代码是不同的转换

bubuko.com,布布扣
 private BitmapImage toImage(BitMatrix matrix)
        {
            try
            {
                int width = matrix.Width;
                int height = matrix.Height;

                Bitmap bmp = new Bitmap(width, height);
            
               // byte[] pixel = new byte[width * height];

                for (int x = 0; x <height ; x++)
                {
                    for (int y = 0; y < width; y++)
                    {
                        if (bitMatrix[x, y])
                        {
                            bmp.SetPixel(x,y,System.Drawing.Color.Black);
                        }
                        else
                        {
                            bmp.SetPixel(x, y, System.Drawing.Color.White);
                        }
                    }
                }

                return ConvertBitmapToBitmapImage(bmp);
            }
            catch (Exception ex)
            {
                throw ex;
            }
           
        }
        private static BitmapImage ConvertBitmapToBitmapImage(Bitmap wbm)
        {
            BitmapImage bimg = new BitmapImage();
            
            using (MemoryStream stream = new MemoryStream())
            {
                wbm.Save(stream , System.Drawing.Imaging.ImageFormat.Png);

                bimg.BeginInit();
                stream.Seek(0, SeekOrigin.Begin);
                bimg.StreamSource = stream;
                bimg.CacheOption = BitmapCacheOption.OnLoad;
                bimg.EndInit();
            }
            return bimg;

        }
bubuko.com,布布扣

 希望对你有一点点帮助!

【WPF】生成二维码

原文:http://www.cnblogs.com/wywnet/p/3559917.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!