ASP.NET 生成随机验证码
我一直觉得用第三方控件生成的验证码太花了,用户体验不好,有的很难看清楚到底是什么,还是那种比较清楚一点的给人的感觉好点。
/// <summary>
/// 这个方法用来生成随机验证码
/// </summary>
private void ShowCode()
{
Random ran = new Random();
int intRandom = ran.Next(10001, 99999);
//将随机数写入Session
Session.RemoveAll();
Session["RandCode"] = intRandom;
//字体名
string strFontName = "Arial";
//字体大小
int intFontSize = 9;
//图像宽
int intWidth = 50;
//图像长
int intHeight = 18;
//背景颜色
Color bgColor = ColorTranslator.FromHtml("#EFF3FF");
//前景色
Color foreColor = ColorTranslator.FromHtml("#00ff00");
//字体
Font forFont = new Font(strFontName, intFontSize, FontStyle.Bold);
//生成图片
Bitmap newBitmap = new Bitmap(intWidth, intHeight, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(newBitmap);
//定义一个四方形框与字片一样大小
Rectangle newRect = new Rectangle(0, 0, intWidth, intHeight);
//背景色
g.FillRectangle(new SolidBrush(bgColor), newRect);
//写字
g.DrawString(intRandom.ToString(), forFont, new SolidBrush(foreColor), 2, 2);
MemoryStream mStream = new MemoryStream();
//存入MemoryStream
newBitmap.Save(mStream, ImageFormat.Gif);
g.Dispose();
newBitmap.Dispose();
//发送
//Response.ClearContent();
Response.ContentType = "image/GIF";
FileStream fis = new FileStream(MapPath("images/") + "yanzheng.gif", FileMode.Create);
fis.Write(mStream.ToArray(), 0, mStream.ToArray().Length);
fis.Close();
this.Image1.ImageUrl = "images/yanzheng.gif";
//Response.End();
}
在项目里面指定一个文件夹命名为images,这样就OK了。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?