前台:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body >
<strong><span style="font-size:12px;color:#ff0000;"> <img style="width:300px;height:300px;" </span><span style="font-size:24px;color:#ff0000;">src="Handler1.ashx"</span><span style="font-size:12px;color:#ff0000;">/></span></strong>
</body>
</html>
解释:我这里把img的图片的路径直接指定为一般处理程序。一般处理程序再返回二进制数据即可
后台:
<strong><span style="font-size:14px;color:#ff0000;">using Gma.QrCodeNet.Encoding;
using Gma.QrCodeNet.Encoding.Windows.Render;</span></strong>
//这两个命名空间非常重要,用来生成二维码的
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
namespace QRCode
{
/// <summary>
/// Handler1 的摘要说明
/// </summary>
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
using (var ms = new MemoryStream())
{
string stringtest = "http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
QRCodeHelper.GetQRCode(stringtest, ms);
context.Response.ContentType = "image/Png";
context.Response.OutputStream.Write(ms.GetBuffer(), 0, (int)ms.Length);
context.Response.End();
}
}
public class QRCodeHelper//生成二维码的方法
{
/// <summary>
/// 获取二维码
/// </summary>
/// <param name="strContent">待编码的字符</param>
/// <param name="ms">输出流</param>
///<returns>True if the encoding succeeded, false if the content is empty or too large to fit in a QR code</returns>
public static bool GetQRCode(string strContent, MemoryStream ms)
{
ErrorCorrectionLevel Ecl = ErrorCorrectionLevel.M; //误差校正水平
string Content = strContent;//待编码内容
QuietZoneModules QuietZones = QuietZoneModules.Two; //空白区域
int ModuleSize = 12;//大小
var encoder = new QrEncoder(Ecl);
QrCode qr;
if (encoder.TryEncode(Content, out qr))//对内容进行编码,并保存生成的矩阵
{
var render = new GraphicsRenderer(new FixedModuleSize(ModuleSize, QuietZones));
render.WriteToStream(qr.Matrix, ImageFormat.Png, ms);
}
else
{
return false;
}
return true;
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}