欢迎光临

木子屋

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

作者: dnawo

日期: 2012-10-12 03:39 PM

分类: Web编程

内容: 复制内容到剪贴板 程序代码<%@ 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)

登录

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 0.906 ms

返回

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

你没有权限发表评论

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 0.906 ms

返回

暂无评论

返回

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 0.938 ms

返回