.NET 二维码生成(ThoughtWorks.QRCode) – jiangys – 博客园

2018年11月28日 分类: C#

来源: .NET 二维码生成(ThoughtWorks.QRCode) – jiangys – 博客园

引用ThoughtWorks.QRCode.dll (源代码里有)

1、简单二维码生成及解码代码:

复制代码
        //生成二维码方法一
        private void CreateCode_Simple(string nr)
        {
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            qrCodeEncoder.QRCodeScale = 4;
            qrCodeEncoder.QRCodeVersion = 8;
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
            //System.Drawing.Image image = qrCodeEncoder.Encode("4408810820 深圳-广州 小江");
            System.Drawing.Image image = qrCodeEncoder.Encode(nr);
            string filename = DateTime.Now.ToString("yyyymmddhhmmssfff").ToString() + ".jpg";
            string filepath = Server.MapPath(@"~\Upload") + "\\" + filename;
            System.IO.FileStream fs = new System.IO.FileStream(filepath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
            image.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);

            fs.Close();
            image.Dispose();
            //二维码解码
            var codeDecoder = CodeDecoder(filepath);
        }

        /// <summary>
        /// 二维码解码
        /// </summary>
        /// <param name="filePath">图片路径</param>
        /// <returns></returns>
        public string CodeDecoder(string filePath)
        {
            if (!System.IO.File.Exists(filePath))
                return null;
            Bitmap myBitmap = new Bitmap(Image.FromFile(filePath));
            QRCodeDecoder decoder = new QRCodeDecoder();
            string decodedString = decoder.decode(new QRCodeBitmapImage(myBitmap));
            return decodedString;
        }
复制代码

2、源代码演示,相对复杂的生成方式:

界面效果:

前端代码:

复制代码
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Code</title>
    <script src="~/Scripts/jquery-1.10.2.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#createCode").click(function () {
                var strData = $("#strData").val();
                var level = $("#level").val();
                var encoding = $("#encoding").val();
                var version = $("#version").val();
                var scale = $("#scale").val();

                $.post("/home/CreateCode_Choose", { strData: strData, level: level, qrEncoding: encoding, version: version, scale: scale }, function (data) {
                    $("img").attr("src", data);
                });
            });

        });

    </script>
</head>
<body>
    <div>
        <p>要生成的文字(支持中文):<input id="strData" type="text" value="123456 测试" /></p>
        <p>
            Encoding:<select id="encoding">
                <option value="Byte">Byte</option>
                <option value="AlphaNumeric">AlphaNumeric</option>
                <option value="Numeric">Numeric</option>
            </select>

        </p>
        <p>
            Correction Level:<select id="level">
                <option value="M">M</option>
                <option value="L">L</option>
                <option value="Q">Q</option>
                <option value="H">H</option>
            </select>
        </p>
        <p>Version:<input id="version" type="text" value="8" /></p>
        <p>scale:<input id="scale" type="text" value="4" /></p>
        <img src="" alt="" />
        <input id="createCode" type="button" value="生成" />
    </div>
</body>
</html>
复制代码

后台:

复制代码
        /// 生成二维码
        /// </summary>
        /// <param name="strData">要生成的文字或者数字,支持中文。如: "4408810820 深圳-广州" 或者:4444444444</param>
        /// <param name="qrEncoding">三种尺寸:BYTE ,ALPHA_NUMERIC,NUMERIC</param>
        /// <param name="level">大小:L M Q H</param>
        /// <param name="version">版本:如 8</param>
        /// <param name="scale">比例:如 4</param>
        /// <returns></returns>
        public ActionResult CreateCode_Choose(string strData, string qrEncoding, string level, int version, int scale)
        {
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            string encoding = qrEncoding;
            switch (encoding)
            {
                case "Byte":
                    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
                    break;
                case "AlphaNumeric":
                    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.ALPHA_NUMERIC;
                    break;
                case "Numeric":
                    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.NUMERIC;
                    break;
                default:
                    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
                    break;
            }

            qrCodeEncoder.QRCodeScale = scale;
            qrCodeEncoder.QRCodeVersion = version;
            switch (level)
            {
                case "L":
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.L;
                    break;
                case "M":
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
                    break;
                case "Q":
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.Q;
                    break;
                default:
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H;
                    break;
            }
            //文字生成图片
            Image image = qrCodeEncoder.Encode(strData);
            string filename = DateTime.Now.ToString("yyyymmddhhmmssfff").ToString() + ".jpg";
            string filepath = Server.MapPath(@"~\Upload") + "\\" + filename;
            //如果文件夹不存在,则创建
            //if (!Directory.Exists(filepath))
            //    Directory.CreateDirectory(filepath);
            System.IO.FileStream fs = new System.IO.FileStream(filepath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
            image.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
            fs.Close();
            image.Dispose();
            return Content(@"/Upload/" + filename);
        }
复制代码

ThoughtWorks.QRCode.Codec.QRCodeEncoder encoder = new QRCodeEncoder();
encoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;//编码方式(注意:BYTE能支持中文,ALPHA_NUMERIC扫描出来的都是数字)
encoder.QRCodeScale = 4;//大小(值越大生成的二维码图片像素越高)
encoder.QRCodeVersion = 0;//版本(注意:设置为0主要是防止编码的字符串太长时发生错误)
encoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;//错误效验、错误更正(有4个等级)
String qrdata = “二维码信息”;
System.Drawing.Bitmap bp = encoder.Encode(qrdata.ToString(), Encoding.GetEncoding(“GB2312”));
Image image = bp;
pictureBox1.Image = bp;
保存二维码图片:
SaveFileDialog sf = new SaveFileDialog();
sf.Title = “选择保存文件位置”;
sf.Filter = “保存图片(*.jpg) |*.jpg|所有文件(*.*) |*.*”;
//设置默认文件类型显示顺序
sf.FilterIndex = 1;
//保存对话框是否记忆上次打开的目录
sf.RestoreDirectory = true;
if (sf.ShowDialog() == DialogResult.OK)
{
Image im = this.pictureBox1.Image;
//获得文件路径
string localFilePath = sf.FileName.ToString();
if (sf.FileName != “”)
{
string fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf(“\\”) + 1);//获取文件名,不带路径
// newFileName = fileNameExt+DateTime.Now.ToString(“yyyyMMdd”)  ;//给文件名后加上时间
string FilePath = localFilePath.Substring(0, localFilePath.LastIndexOf(“.”));  //获取文件路径,带文件名,不带后缀
string fn = sf.FileName;
pictureBox1.Image.Save(FilePath +”-“+ DateTime.Now.ToString(“yyyyMMdd”) + “.jpg”);

}
}
//解析二维码信息
// QRCodeDecoder decoder = new QRCodeDecoder();
//  String decodedString = decoder.decode(new QRCodeBitmapImage(new Bitmap(pictureBox1.Image)));
//this.label3.Text = decodedString;

 


标签:
本文的评论功能被关闭了.
备案信息冀ICP 0007948