ASP.NET实现二维码(QRCode)的创建和读取实例_实用技巧

本文实例讲述了ASP.NET实现二维码(QRCode)的创建和读取方法。分享给大家供大家参考。具体分析如下:

概述:

QR二维码比其他二维码相比,具有识读速度快、数据密度大、占用空间小的优势。QR码的三个角上有三个寻象图形,使用CCD识读设备来探测码的位置、大小、倾斜角度、并加以解码,实现360读高速识读。每秒可以识读30个含有100个字符QR码。QR码容量密度 大,可以放入1817个汉字、7089个数字、4200个英文字母。QR码用数据压缩方式表示汉字,仅用13bit即可表示一个汉字,比其他二维条码表示 汉字的效率提高了20%。QR具有4个等级的纠错功能,即使破损或破损也能够正确识读。QR码抗弯曲的性能强,通过QR码中的每隔一定的间隔配置有校正图 形,从码的外形来求得推测校正图形中心点与实际校正图形中心点的误差来修正各个模快的中心距离,即使将QR码贴在弯曲的物品上也能够快速识读。QR码可以分割成16个QR码,可以一次性识读数个分割码,适应于印刷面积有限及细长空间印刷的需要。此外微型QR码可以在1厘米的空间内放入35个数字或9个汉字 或21个英文字母,适合对小型电路板对ID号码进行采集的需要。

QRCode点击此处本站下载(支持中文)

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

二、ASPX页面(两个jquery的js文件请自行去官网下载):

复制代码 代码如下:

<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文件

复制代码 代码如下:

$(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=set&txt_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,没有判断目录是否存在等问题,请自行建立或者更改代码。

复制代码 代码如下:

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进制或16进制转换为中文
    /// </summary>
    /// <param name="name">要转换的字符串</param>
    /// <param name="fromBase">进制(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程序设计有所帮助。

时间: 2024-12-08 11:03:22

ASP.NET实现二维码(QRCode)的创建和读取实例_实用技巧的相关文章

C#开发微信 二维码鼠标滑动 图像显示隐藏效果(推荐)_实用技巧

客户端微信在二维码状态下,鼠标滑过,会有一张手机的图片滑动滑出,从隐藏到显示,从显示到隐藏. 思路很简单:1.设置透明度:2.给个移动的位移 先看下做的效果 整体代码也不难,就是给Image控件设置动画效果. <Grid x:Name="grid_content" Background="WhiteSmoke" Grid.Row="1"> <Grid.Triggers> <EventTrigger RoutedEve

ASP.NET(C#) Web Api通过文件流下载文件的实例_实用技巧

下载文件到本地是很多项目开发中需要实现的一个很简单的功能.说简单,是从具体的代码实现上来说的,.NET的文件下载方式有很多种,本示例给大家介绍的是ASP.NET Web Api方式返回HttpResponseMessage下载文件到本地.实现的方法很简单,其中就是读取服务器的指定路径文件流,将其做为返回的HttpResponseMessage的Content.直接贴出DownloadController控件器的代码: using System; using System.Collections.

asp.net继承IHttpHandler接口实现给网站图片添加水印功能实例_实用技巧

本文实例讲述了asp.net继承IHttpHandler接口实现给网站图片添加水印功能.分享给大家供大家参考,具体如下: 先展示图片效果: 1. 在App_Code下添加类文件,命名为ImageSY 文件内容如下 public class ImageSY : IHttpHandler { public ImageSY() { // //TODO: 在此处添加构造函数逻辑 // } #region IHttpHandler 成员 public bool IsReusable { get { ret

在ASP.NET Core中实现一个Token base的身份认证实例_实用技巧

以前在web端的身份认证都是基于Cookie | Session的身份认证, 在没有更多的终端出现之前,这样做也没有什么问题,但在Web API时代,你所需要面对的就不止是浏览器了,还有各种客户端,这样就有了一个问题,这些客户端是不知道cookie是什么鬼的. (cookie其实是浏览器搞出来的小猫腻,用来保持会话的,但HTTP本身是无状态的, 各种客户端能提供的无非也就是HTTP操作的API) 而基于Token的身份认证就是应对这种变化而生的,它更开放,安全性也更高. 基于Token的身份认证

EasyUI Tree+Asp.net实现权限树或目录树导航的简单实例_实用技巧

复制代码 代码如下: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Main.aspx.cs" Inherits="Manage_Main" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR

ASP.NET生成二维码的方法总结_实用技巧

本文实例总结了ASP.NET生成二维码的方法.分享给大家供大家参考,具体如下: 分享一例c#生成二维码的代码,直接引用ThoughtWorks.QRCode.dll 类生成二维码,有需要的朋友参考下. 方法1.直接引用ThoughtWorks.QRCode.dll 类,生成二维码. 代码示例: ThoughtWorks.QRCode.Codec.QRCodeEncoder encoder = new QRCodeEncoder(); encoder.QRCodeEncodeMode = QRCo

ios开发之Swift二维码QRCode的读取(从图片读取 ,或通过摄像头扫描)

1,直接读取图片中的二维码 使用 CIDetector 可以很方便的检测并读取二维码.下面是一个从 UIImage 中读取二维码的样例,我们要把图片上所有的二维码信息都打印出来. 开发之Swift二维码QRCode的读取(从图片读取 ,或通过摄像头扫描)-qrcode 读取二维码">    代码如下 复制代码 import UIKit   class ViewController: UIViewController {       override func viewDidLoad() {

Java实现二维码QRCode的编码和解码与示例解析_java

Java实现二维码QRCode的编码和解码 涉及到的一些主要类库,方便大家下载: 编码lib:Qrcode_swetake.jar   (官网介绍-- http://www.swetake.com/qr/index-e.html)             解码lib:qrcode.jar                 (官网介绍-- http://sourceforge.jp/projects/qrcode/) [一].编码: Java代码QRCodeEncoderHandler.java p

vc++-二维字符串SAFEARRAY的创建和读取

问题描述 二维字符串SAFEARRAY的创建和读取 各大神好,下面是我创建的字符串二维数组: SAFEARRAYBOUND Bound[2]; Bound[0].lLbound=0; Bound[0].cElements=2; Bound[1].lLbound=0; Bound[1].cElements=3; SAFEARRAY* pArray=SafeArrayCreate(VT_BSTR,2,Bound); CString strInfos[3][3]; strInfos[0][0] = "