一、原理
1.在webservice服务端,新建一个Bitmap对象,将验证码字符串、干扰线和干扰点绘制到此Bitmap上——>转换为字节数组——>Base64字符串
2.<img src="data:image/jpeg;base64,此处base64字符串"/>
二、生成验证码图片字节数据
public byte[] CreateValidateGraphic(string validateCode)
{
var image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), );
var g = Graphics.FromImage(image);
try
{
//生成随机生成器
var random = new Random();
//清空图片背景色
g.Clear(Color.White);
//画图片的干扰线
for (int i = ; i < ; i++)
{
var x1 = random.Next(image.Width);
var x2 = random.Next(image.Width);
var y1 = random.Next(image.Height);
var y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
//Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
string[] fontName = { "华文新魏", "宋体", "圆体", "黑体", "隶书" };
var font = new Font(fontName[new Random().Next(, validateCode.Length)], , (FontStyle.Bold | FontStyle.Italic));
var brush = new LinearGradientBrush(new Rectangle(, , image.Width, image.Height),
Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(validateCode, font, brush, , );
//画图片的前景干扰点
for (var i = ; i < ; i++)
{
var x = random.Next(image.Width);
var y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//画图片的边框线
g.DrawRectangle(new Pen(Color.Silver), , , image.Width - , image.Height - );
//保存图片数据
var stream = new MemoryStream();
image.Save(stream, ImageFormat.Jpeg);
//输出图片流
return stream.ToArray();
}
finally
{
g.Dispose();
image.Dispose();
}
}
三、字节转base64
Convert.ToBase64String(CreateValidateGraphic("123T"));
四、在html标签<img/>中显示baser64字符串表示的图片
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="VerificationCodePage.aspx.cs" Inherits="VerificationCode.Pages.VerificationCodePage" %>
<!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>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
</head>
<body>
<div>
<img id="verification" src="" style="width:200px;height:100px;" />
</div>
<script type="text/javascript">
var CreatVerificationCode = function () {
var number = Math.floor(Math.random() * 8999) + 1000;
$.ajax({
type: "post",
url: "../WebService/VerificationCodeWebService.asmx/GetValidateCode",
data: '{ number: ' + number + '}',
dataType: "json",
contentType: "application/json;charset=utf8",
success: function (data) {
$("#verification").attr("src", "data:image/jpeg;base64," + data.d);
},
error: function (data) {
alert(data);
}
});
}
$("#verification").click(CreatVerificationCode);
CreatVerificationCode();
</script>
</body>
</html>
工程VerificationCode验证码.rar下载地址:链接: http://pan.baidu.com/s/1i5lmYGX 密码: unjr