木子屋 Dnawo's BLOG

C#调用ZXing生成二维码简单示例

👤 dnawo 📅 2012-10-12 👁 9212 👍 0 💬 0 🔄 本站原创
<%@ WebHandler Language="C#" Class="Default" %>

using System;
using System.Collections;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web;
using com.google.zxing;
using com.google.zxing.common;
using com.google.zxing.qrcode.decoder;

public class Default : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        CreateQRCode(context);
    }

    /// <summary>
    /// 生成二维码
    /// </summary>
    /// <param name="context"></param>
    private void CreateQRCode(HttpContext context)
    {
        context.Response.ContentType = "image/jpeg";
        int width = 300; //宽度
        int height = 300; //高度
        string content = "http://www.mzwu.com/"; //内容
        Color fgColor = ColorTranslator.FromHtml("0xFF000000"); //前景色
        Color bgColor = ColorTranslator.FromHtml("0xFFFFFFFF"); //背景色
        Hashtable hints = new Hashtable();
        hints.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//容错能力
        hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");//字符集
        ByteMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        using (Bitmap bmap = new Bitmap(width, height, PixelFormat.Format32bppArgb))
        {
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    bmap.SetPixel(x, y, matrix.get_Renamed(x, y) != -1 ? fgColor : bgColor);
                }
            }
            bmap.Save(context.Response.OutputStream, ImageFormat.Jpeg);
        }
    }

    /// <summary>
    /// 解析二维码
    /// </summary>
    /// <param name="img"></param>
    /// <returns></returns>
    private string ParseQRCode(string img)
    {
        using (Bitmap bmap = new Bitmap(Image.FromFile(img)))
        {
            Hashtable hints = new Hashtable();
            hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");//字符集
            LuminanceSource source = new RGBLuminanceSource(bmap, bmap.Width, bmap.Height);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            Result result = new MultiFormatReader().decode(bitmap, hints);
            return result.Text;
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

图片

参考资料

[1].ZXing:http://code.google.com/p/zxing/
[2].[C#]透過 zxing 產生QR Code:http://www.dotblogs.com.tw/jaigi/archive/2012/03/26/71049.aspx

评论(0)

暂无评论。

计算题
评论需审核通过后显示
← 上一篇 Google二维码生成接口(API)说明 下一篇 → QRcode常见数据格式