在线时间:8:00-16:00
132-9538-2358
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Asp.Net-Codeusing System;using System.Drawing;using System.Drawing.Imaging;using System.IO;
public partial class _Default : System.Web.UI.Page{ private Random Rnd; private string StrCode;
protected void Page_Load(object sender, EventArgs e) { MemoryStream ImageStream; ImageStream = GetImages(80, 12, 6, "#FFFFFF"); ShowImage(ImageStream); ImageStream.Close(); Session["ValiCode"] = StrCode; Response.End(); }
/// <summary> /// 生成验证码图像 /// </summary> /// <param name="ImageWidth">图片大小</param> /// <param name="FontSize">字体大小</param> /// <param name="CharNumber">生成字符数</param> /// <param name="BackgroundColor">背景色</param> /// <returns></returns> private MemoryStream GetImages(int ImageWidth, int FontSize, int CharNumber, string BackgroundColor) { int ImageHeight = 5; Bitmap TempBitmap; Graphics TempGraphics; Color ColorBack = ColorTranslator.FromHtml(BackgroundColor); TempBitmap = new Bitmap(ImageWidth, 4 * ImageHeight, PixelFormat.Format24bppRgb); TempGraphics = Graphics.FromImage(TempBitmap); TempGraphics.FillRectangle(new SolidBrush(ColorBack), new Rectangle(0, 0, ImageWidth, 5 * ImageHeight)); string ImageNumber = null, ShowCode = null; Color ColorFont; int ShowCodeFontSize; Font ShowCodeFont; Rnd = new Random(); for (int i = 0; i < CharNumber; i++) { ShowCode = GetChar(); ImageNumber += ShowCode; ShowCodeFontSize = Convert.ToInt32(3 * Rnd.NextDouble() + (FontSize - 2)); ColorFont = ColorTranslator.FromHtml(GetColor()); ShowCodeFont = new Font("Verdana", ShowCodeFontSize, FontStyle.Bold); TempGraphics.DrawString(ShowCode, ShowCodeFont, new SolidBrush(ColorFont), Convert.ToInt32(FontSize / 2) + i * FontSize, Convert.ToInt32(ImageHeight * 0.125 * Rnd.NextDouble() + ImageHeight * 0.08)); } StrCode = ImageNumber.Trim().ToLower(); FontSize = FontSize * 4; ImageHeight = Convert.ToInt32(2.5 * FontSize); MemoryStream TempStream = new MemoryStream(); TempBitmap.Save(TempStream, ImageFormat.Gif); TempGraphics.Dispose(); TempBitmap.Dispose(); TempStream.Close(); return TempStream; }
/// <summary> /// 写入Http输出流 /// </summary> /// <param name="ShowStream">内存流</param> private void ShowImage(MemoryStream ShowStream) { Response.ClearContent(); Response.ContentType = "image/gif"; Response.BinaryWrite(ShowStream.ToArray()); }
/// <summary> /// 获取随机字符 /// </summary> /// <returns></returns> private string GetChar() { char[] CharArray = new char[2]; CharArray[0] = (char)(48 + Rnd.Next(0, 10)); CharArray[1] = (char)(65 + Rnd.Next(0, 6)); return CharArray[Rnd.Next(0, 2)].ToString(); }
/// <summary> /// 获取随机颜色 /// </summary> /// <returns></returns> private string GetColor() { int ColorR, ColorG, ColorB; ColorR = 20 + Rnd.Next(0, 180); ColorG = 20 + Rnd.Next(0, 180); ColorB = 20 + Rnd.Next(0, 180); if (ColorR > 150 && ColorR > 150 && ColorR > 150) { ColorR = 20 + Rnd.Next(0, 150); } return "#" + Convert.ToString(ColorR, 16) + Convert.ToString(ColorG, 16) + Convert.ToString(ColorB, 16); }
}
评论
请发表评论