C# 生成二维码

         在C#中直接引用ThoughtWorks.QRCode.dll 类, 

           QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;    //编码方式(注意:BYTE能支持中文,ALPHA_NUMERIC扫描出来的都是数字)
            qrCodeEncoder.QRCodeScale = 4;                                                    //大小(值越大生成的二维码图片像素越高)
            qrCodeEncoder.QRCodeVersion = 8;                                               //版本(注意:设置为0主要是防止编码的字符串太长时发生错误)
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;       //错误效验、错误更正(有4个等级)
            string data = "http://www.xxxxx.com/register.aspx?refpeople=" + username + "";   //二维码信息
            context.Response.Write(data);
            System.Drawing.Bitmap image = qrCodeEncoder.Encode(data);
            System.IO.MemoryStream MStream = new System.IO.MemoryStream();
            image.Save(MStream, System.Drawing.Imaging.ImageFormat.Png);
            context.Response.ClearContent();
            context.Response.ContentType = "image/Png";
            context.Response.BinaryWrite(MStream.ToArray());
            string path = context.Server.MapPath("~/uploadfile/twocode");

            Directory.CreateDirectory(path);
            path = path + "\\" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".png";
            FileStream fs = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite);
            BinaryWriter bw = new BinaryWriter(fs, UTF8Encoding.UTF8);
            byte[] by = MStream.ToArray();
            for (int i = 0; i < MStream.ToArray().Length; i++)
                bw.Write(by[i]);
            fs.Close();

            string relativePath = "/uploadfile/twocode/" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".png";

posted @ 2015-09-23 09:52  CreativeSpirit  阅读(320)  评论(0编辑  收藏  举报