C# MVC4 QRCode二维码生成

来源:互联网 发布:php文件上传与下载 编辑:程序博客网 时间:2024/05/22 01:27

引用微软二维码类库:ThoughtWorks.QRCode.dll

在控制器中(Controllers)引用命名空间:

using System.Drawing;
using ThoughtWorks.QRCode.Codec;
using ThoughtWorks.QRCode.Codec.Data;
using ThoughtWorks.QRCode.Codec.Util;

创建生成二维码方法:

//生成二维码
        public ContentResult Erweima(string id)
        {
            string bmp = "http://www.shenraytech.com/Products/Index/";
            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(bmp + id);
            //生成新的(时间)图片名称
            string filename = DateTime.Now.ToString("yyyymmddhhmmssfff").ToString() + ".jpg";
            string filepath = Server.MapPath(@"~\picture") + "\\" + filename;
            //验证文件夹中是否有重命名的图片名,保证唯一性
            System.IO.FileStream fs = new System.IO.FileStream(filepath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
            //保存图片(以文件流的方式,保存到picture文件夹下)
            image.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
            fs.Close();
            image.Dispose();
            //返回图片名称
            return Content(filename);

        }

在视图中(网页):

<p><input type="text" id="id" /><input type="button" id="btn" /></p>
    <img id="sss" src="/Images/" alt="" />
    <input type="text" id="ss" />
    <script type="text/javascript">
        //$("#btn").click(function () {
        //    $.post("/Erweima/Erweima", { id: $("#id").val() }, function (data) { $("#sss").attr("src", data); $("#ss").val(data); });
        //})
        $("#btn").click(function () {
            $.ajax({
                url: "/Erweima/Erweima",
                typr: "post",
                data: { "id": $("#id").val() },
                dataType: "text",
                success: function (resule) {
                    var ss = "/Images/" + resule;
                    $("#sss").attr("src", ss);
                    $("#ss").val(resule);
                }
            });
        });
    </script>



0 0
原创粉丝点击