主頁 > 知識庫 > ASP.NET實現(xiàn)二維碼(QRCode)的創(chuàng)建和讀取實例

ASP.NET實現(xiàn)二維碼(QRCode)的創(chuàng)建和讀取實例

熱門標(biāo)簽:河南語音外呼系統(tǒng)公司 t3出行地圖標(biāo)注怎么做 威海電銷 400免費電話怎么辦理 河北網(wǎng)絡(luò)回?fù)芡夂粝到y(tǒng) 400電話辦理最優(yōu)質(zhì) 外呼電銷機器人軟件 關(guān)于宗地圖標(biāo)注技術(shù)規(guī)范 寧夏機器人電銷

本文實例講述了ASP.NET實現(xiàn)二維碼(QRCode)的創(chuàng)建和讀取方法。分享給大家供大家參考。具體分析如下:

概述:

QR二維碼比其他二維碼相比,具有識讀速度快、數(shù)據(jù)密度大、占用空間小的優(yōu)勢。QR碼的三個角上有三個尋象圖形,使用CCD識讀設(shè)備來探測碼的位置、大小、傾斜角度、并加以解碼,實現(xiàn)360讀高速識讀。每秒可以識讀30個含有100個字符QR碼。QR碼容量密度 大,可以放入1817個漢字、7089個數(shù)字、4200個英文字母。QR碼用數(shù)據(jù)壓縮方式表示漢字,僅用13bit即可表示一個漢字,比其他二維條碼表示 漢字的效率提高了20%。QR具有4個等級的糾錯功能,即使破損或破損也能夠正確識讀。QR碼抗彎曲的性能強,通過QR碼中的每隔一定的間隔配置有校正圖 形,從碼的外形來求得推測校正圖形中心點與實際校正圖形中心點的誤差來修正各個??斓闹行木嚯x,即使將QR碼貼在彎曲的物品上也能夠快速識讀。QR碼可以分割成16個QR碼,可以一次性識讀數(shù)個分割碼,適應(yīng)于印刷面積有限及細(xì)長空間印刷的需要。此外微型QR碼可以在1厘米的空間內(nèi)放入35個數(shù)字或9個漢字 或21個英文字母,適合對小型電路板對ID號碼進(jìn)行采集的需要。

QRCode點擊此處本站下載(支持中文)

一、項目引用QRCode的DLL文件(ThoughtWorks.QRCode.dll)

二、ASPX頁面(兩個jquery的js文件請自行去官網(wǎng)下載):

復(fù)制代碼 代碼如下:
html xmlns="http://www.w3.org/1999/xhtml">
head runat="server">
    title>二維碼工具測試/title>
    script type="text/javascript" src="../../Scripts/Jquery/jquery-1.6.2.js">/script>
    script type="text/javascript" src="../../Scripts/Jquery/jquery.form.js">/script>   
    script type="text/javascript" src="js/test.js">/script>
    style type="text/css">
        .style1
        {
            width: 100%;
        }
        #txt_qr
        {
            width: 632px;
        }
    /style>
/head>
body>
    div>
        table class="style1">
            tr>
                td>
                    輸入文字:
                /td>
                td>
                    input type="text" id="txt_qr" name="txt_qr" />
                /td>
            /tr>
            tr>
                td>
                    二維碼圖片
                /td>
                td>
                    img id="qrimg" alt="二維碼圖片" />
                /td>
            /tr>
            tr>
                td>
                    生成選項
                /td>
                td>
                    Encoding:select id="Encoding">
                        option value="Byte">Byte/option>
                        option value="AlphaNumeric">AlphaNumeric/option>
                        option value="Numeric">Numeric/option>
                    /select>
                    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>
                    Version:input id="txt_ver" type="text" value="7" />(1-40) Size:input id="txt_size"
                        type="text" value="4" />
                /td>
            /tr>
            tr>
                td colspan="4">
                    input type="button" onclick="getQrImg();" value="生成二維碼" />
                /td>
            /tr>
            tr>
                td>
                    form id="qrForm" action="Ashx/test.ashx" method="post" enctype="multipart/form-data">
                    input type="file" id="file_qr" name="file_qr" />input type="submit" value="讀取二維碼" />
                    /form>
                /td>
                td colspan="1">
                    img id="img_qr" alt="要讀取的圖片" />br />
                    input id="txt_readqr" type="text" />
                /td>
            /tr>
        /table>
    /div>
/body>
/html>

三、test.js文件

復(fù)制代碼 代碼如下:
$(document).ready(function ()
{
    var options = {
        beforeSubmit: showRequest, 
        success: showResponse,         
        dataType: 'json',
        clearForm: true,           
        error: function (request, message, ex)
        {
            alert('錯誤:' + message);
        }
    };    
    $('#qrForm').ajaxForm(options);
});
function showRequest(formData, jqForm, options)
{
    return true;
}
function showResponse(responseText, statusText, xhr, $form)
{
    if (responseText[0].count == 0)
    {
        alert(responseText[0].list[0].error);
        return false;
    }
    $("#img_qr").attr("src", responseText[0].list[0].imgurl);
    $("#txt_readqr").val(responseText[0].list[0].qrtext);
    return false;

}
function getQrImg()
{
    var txt_qr = escape($.trim($("#txt_qr").val()));
    var qrEncoding = $("#Encoding").val(); ;
    var Level = $("#Level").val(); ;
    var txt_ver = $("#txt_ver").val(); ;
    var txt_size = $("#txt_size").val(); ;
    $.ajax({
        type: "GET",
        data: "cmd=settxt_qr=" + txt_qr + "qrEncoding=" + qrEncoding + "Level=" + Level + "txt_ver=" + txt_ver + "txt_size=" + txt_size,
        url: "Ashx/test.ashx",
        dataType: 'text',
        beforeSend: function (x)
        {
            x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        },
        success: function (json)
        {
            var dataObj = eval(json);            
            $("#qrimg").attr("src", dataObj[0].list[0].imgurl);           
            return false;
        },
        error: function (request, message, ex)
        {
            alert("錯誤:" + message);
        }
    });
}


四、test.ashx,沒有判斷目錄是否存在等問題,請自行建立或者更改代碼。
復(fù)制代碼 代碼如下:
using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Text.RegularExpressions;
using ThoughtWorks.QRCode.Codec;
using ThoughtWorks.QRCode.Codec.Data;
using ThoughtWorks.QRCode.Codec.Util;
public class test : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        string cmd = context.Request["cmd"] == null ? "get" : context.Request["cmd"].ToString();
        string filename = string.Empty;
        string filepath = string.Empty;
        switch (cmd)
        {
            case "get":
                if (context.Request.Files.Count > 0)
                {
                    for (int j = 0; j context.Request.Files.Count; j++)
                    {
                        filename = Guid.NewGuid().ToString() + "_tmp.jpg";
                        filepath = context.Server.MapPath(@"~\Utilty\QRCode\upload") + "\\" + filename;
                        string qrdecode = string.Empty;
                        HttpPostedFile uploadFile = context.Request.Files[j];
                        uploadFile.SaveAs(filepath);

                        QRCodeDecoder decoder = new QRCodeDecoder();                        
                        Bitmap bm = new Bitmap(filepath);
                        qrdecode = decoder.decode(new QRCodeBitmapImage(bm));
                        bm.Dispose();                 
                       
                        context.Response.Write("[{\"count\":1,\"list\":[{\"imgurl\":\"upload/" + filename + "\",\"qrtext\":\"" + qrdecode + "\"}]}]");
                    }
                }
                else
                {
                    context.Response.Write("[{\"count\":0,\"list\":[{\"error\":\"沒有上傳文件\"}]}]");
                }
                break;
            case "set":
                string txt_qr =ConverToGB(context.Request["txt_qr"].ToString().Trim(), 16);
                string qrEncoding = context.Request["qrEncoding"].ToString();
                string Level = context.Request["Level"].ToString();
                string txt_ver = context.Request["txt_ver"].ToString();
                string txt_size = context.Request["txt_size"].ToString();

                QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
                String encoding = qrEncoding;
                if (encoding == "Byte")
                {
                    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
                }
                else if (encoding == "AlphaNumeric")
                {
                    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.ALPHA_NUMERIC;
                }
                else if (encoding == "Numeric")
                {
                    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.NUMERIC;
                }
                try
                {
                    int scale = Convert.ToInt16(txt_size);
                    qrCodeEncoder.QRCodeScale = scale;
                }
                catch (Exception ex)
                {
                    return;
                }
                try
                {
                    int version = Convert.ToInt16(txt_ver);
                    qrCodeEncoder.QRCodeVersion = version;
                }
                catch (Exception ex)
                {
                    return;
                }
                string errorCorrect = Level;
                if (errorCorrect == "L")
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.L;
                else if (errorCorrect == "M")
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
                else if (errorCorrect == "Q")
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.Q;
                else if (errorCorrect == "H")
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H;

                Image image;
                String data = txt_qr;
                image = qrCodeEncoder.Encode(data);
                filename = Guid.NewGuid().ToString() + ".jpg";
                filepath = context.Server.MapPath(@"~\Utilty\QRCode\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();
                context.Response.Write("[{\"count\":1,\"list\":[{\"imgurl\":\"upload/" + filename + "\"}]}]");

                //context.Response.Write(@"upload\" + filename);
                break;
        }
    }
    /// summary>
    /// 10進(jìn)制或16進(jìn)制轉(zhuǎn)換為中文
    /// /summary>
    /// param name="name">要轉(zhuǎn)換的字符串/param>
    /// param name="fromBase">進(jìn)制(10或16)/param>
    /// returns>/returns>
    public string ConverToGB(string text, int fromBase)
    {
        string value = text;
        MatchCollection mc;
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        switch (fromBase)
        {
            case 10:
                MatchCollection mc1 = Regex.Matches(text, @"#([\d]{5})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                foreach (Match _v in mc1)
                {
                    string w = _v.Value.Substring(2);
                    w = Convert.ToString(int.Parse(w), 16);
                    byte[] c = new byte[2];
                    string ss = w.Substring(0, 2);
                    int c1 = Convert.ToInt32(w.Substring(0, 2), 16);
                    int c2 = Convert.ToInt32(w.Substring(2), 16);
                    c[0] = (byte)c2;
                    c[1] = (byte)c1;
                    sb.Append(Encoding.Unicode.GetString(c));
                }
                value = sb.ToString();

                break;
            case 16:
                mc = Regex.Matches(text, @"\\u([\w]{2})([\w]{2})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                if (mc != null mc.Count > 0)
                {

                    foreach (Match m2 in mc)
                    {
                        string v = m2.Value;
                        string w = v.Substring(2);
                        byte[] c = new byte[2];
                        int c1 = Convert.ToInt32(w.Substring(0, 2), 16);
                        int c2 = Convert.ToInt32(w.Substring(2), 16);
                        c[0] = (byte)c2;
                        c[1] = (byte)c1;
                        sb.Append(Encoding.Unicode.GetString(c));
                    }
                    value = sb.ToString();
                }
                break;
        }
        return value;
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

效果如下圖所示:

PS:感興趣的朋友還可參考本站二維碼工具:http://tools.jb51.net/transcoding/jb51qrcode

希望本文所述對大家的asp.net程序設(shè)計有所幫助。

您可能感興趣的文章:
  • ASP.NET對txt文件相關(guān)操作(讀取、寫入、保存)
  • asp.net cookie的操作,寫入、讀取與操作
  • Asp.Net 文件操作基類(讀取,刪除,批量拷貝,刪除,寫入,獲取文件夾大小,文件屬性,遍歷目錄)
  • asp.net使用npoi讀取excel模板并導(dǎo)出下載詳解
  • Asp.net把圖片存入數(shù)據(jù)庫和讀取圖片的方法
  • asp.net 未能寫入輸出文件--“拒絕訪問的解決辦法
  • asp.net中上傳圖片文件實現(xiàn)防偽圖片水印并寫入數(shù)據(jù)庫
  • asp.net 圖片的讀寫入庫實現(xiàn)代碼
  • asp.net 操作XML 按指定格式寫入XML數(shù)據(jù) WriteXml
  • ASP.NET 動態(tài)寫入服務(wù)器端控件
  • asp.net讀取模版并寫入文本文件

標(biāo)簽:賀州 廣元 吉林 淮北 固原 咸寧 樂山 池州

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《ASP.NET實現(xiàn)二維碼(QRCode)的創(chuàng)建和讀取實例》,本文關(guān)鍵詞  ASP.NET,實現(xiàn),二維,碼,QRCode,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《ASP.NET實現(xiàn)二維碼(QRCode)的創(chuàng)建和讀取實例》相關(guān)的同類信息!
  • 本頁收集關(guān)于ASP.NET實現(xiàn)二維碼(QRCode)的創(chuàng)建和讀取實例的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章