1.2建立一个Web窗体
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!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>
<form id="form1" runat="server">
<div>
<img src="image/1.jpg" />
</div>
</form>
</body>
</html>
2.建立一个HttpHandler的一般程序#3
public class Class1 : IHttpHandler
{
public bool IsReusable => false;
public void ProcessRequest(HttpContext context)
{
String filename = context.Request.PhysicalPath;
Bitmap bitmap = new Bitmap(filename);
Graphics graphics = Graphics.FromImage(bitmap);
graphics.DrawString("侵权必究",new Font("宋体",20,FontStyle.Bold),Brushes.Red,new Point(1,1));
graphics.Flush();
bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
3.效果如下:
4.HttpHandler实现验证码
public class Handler1 : IHttpHandler,IRequiresSessionState
{
//随机数对象
Random Random = new Random();
public bool IsReusable => false;
public void ProcessRequest(HttpContext context)
{
//验证码使用的字符
string strWord = "0123456789QWERTYUIOPASDFGHJKLZXCVBNM";
string NumStr = null;
for (int i = 0; i < 4; i++)
{
NumStr += strWord[Random.Next(0, strWord.Length)].ToString();
}
//将验证码保存到Session中
context.Session["vcode"] = NumStr;
CreateImages(context, NumStr);
}
private void CreateImages(HttpContext context, string numStr)
{
int iwidth = numStr.Length * 13;
//点位图
Bitmap bitmap = new Bitmap(iwidth, 22);
//形成图形和画板
Graphics graphics = Graphics.FromImage(bitmap);
//画板的背景颜色
graphics.Clear(Color.White);
//定义颜色
Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown };
//定义字体
String[] f = { "Verdana", "微软雅黑", "宋体", "Comic Sans MS", "Arial" };
Random random2 = new Random();
//随机输出照点
for (int i = 0; i < 50; i++)
{
int x = random2.Next(bitmap.Width);
int y = random2.Next(bitmap.Height);
//画一个矩形
graphics.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
}
//输出不同字体和颜色的验证码字符
for (int i = 0; i < numStr.Length; i++)
{
int cindex = random2.Next(6);
int findex = random2.Next(5);
Brush brush = new SolidBrush(c[cindex]);
Font font = new Font(f[findex], 10, FontStyle.Bold);
int ii = 4;
if ((i + 1) % 2 == 0)
{
ii = 2;
}
graphics.DrawString(numStr.Substring(i, 1), font, brush, 2 + (i * 12), ii);
}
//画一个边框
graphics.DrawRectangle(new Pen(ColorTranslator.FromHtml("red"), 0), 0, 0, bitmap.Width - 1, bitmap.Height - 1);
//输出到浏览器
MemoryStream ms = new MemoryStream();
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
context.Response.ClearContent();
context.Response.ContentType = "images/gif";
context.Response.BinaryWrite(ms.ToArray());
graphics.Dispose();
bitmap.Dispose();
}
}
}
————————————————
版权声明:本文为CSDN博主「weixin_57128727」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_57128727/article/details/117475473