澳门新浦京娱乐场网站-www.146.net-新浦京娱乐场官网
做最好的网站

澳门新浦京娱乐场网站NET中登陆验证码的生成和

做了个艺术字在线制作网站,整理一下技术代码

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;

一:验证码的生成实现代码

System.Drawing.Text.PrivateFontCollection FM = new PrivateFontCollection();
FM.AddFontFile(Server.MapPath("字体文件路径"));
FontFamily FML = FM.Families[0];

//该类将用于生成验证码图片
public partial class ValidateCode1 : System.Web.UI.Page
{
    private static Pen BorderColor = Pens.DarkGray;

 protected void Page_Load(object sender, EventArgs e)
    {
        string validateCode = CreateValidateCode();//生成验证码
        Bitmap bitmap = new Bitmap(imgWidth, imgHeight);//生成Bitmap图像
        DisturbBitmap(bitmap); //图像背景
        DrewValidateCode(bitmap, validateCode);//绘制验证码图像
        bitmap.Save(Response.OutputStream, ImageFormat.Gif);//保存图像,等待输出

1.安装字体
//程序直接将字体文件安装的系统中。
函数声明:
[DllImport("kernel32.dll", SetLastError = true)] 
static extern int WriteProfileString(string lpszSection, string lpszKeyName, string lpszString); 

这样我们就可以直接读取字体了

    static string[] FontItems = new string[] {       
                                                      "Arial", 
                                                      "Helvetica", 
                                                      "Geneva", 
                                                      "sans-serif", 
                                                      "Verdana"
                                             };
    static Brush[] BrushItems = new Brush[]  {       
                                                      Brushes.OliveDrab,
                                                      Brushes.ForestGreen,
                                                      Brushes.DarkCyan,
                                                      Brushes.LightSlateGray,
                                                      Brushes.RoyalBlue,
                                                      Brushes.SlateBlue,
                                                      Brushes.DarkViolet,
                                                      Brushes.MediumVioletRed,
                                                      Brushes.IndianRed,
                                                      Brushes.Firebrick,
                                                      Brushes.Chocolate,
                                                      Brushes.Peru,
                                                      Brushes.Goldenrod
                                               };

    }

[DllImport("user32.dll")] 
public static extern int SendMessage(int hWnd, // handle to destination window 
uint Msg,  
int wParam,
int lParam
); 

我们可以通过

    //调用函数将验证码生成图片
    protected void Page_Load(object sender, EventArgs e)
    {
        CreateCheckCodeImage(GenerateCheckCode());
    }

    private int codeLen = 4;//验证码长度
    private int fineness = 85;//图片清晰度
    private int imgWidth = 48;//图片宽度
    private int imgHeight = 24;//图片高度
    private string fontFamily = "Times New Roman";//字体名称
    private int fontSize = 14;//字体大小
    //private int fontStyle = 0;//字体样式
    private int posX = 0;//绘制起始坐标X
    private int posY = 0;//绘制坐标Y

[DllImport("gdi32")] 
public static extern int AddFontResource(string lpFileName); 

FontStyle fontStyle = FontStyle.Regular;
fontStyle |= FontStyle.Italic;
fontStyle |= FontStyle.Underline;

...

    //产生五位的随机字符串作为验证码
    private string GenerateCheckCode()
    {
        string checkCode = String.Empty;

    private string CreateValidateCode() //生成验证码
    {
        string validateCode = "";
        Random random = new Random();// 随机数对象
        for (int i = 0; i < codeLen; i )//循环生成每位数值
        {
            int n = random.Next(10);//数字
            validateCode = n.ToString();
        }
        Session["vcode"] = validateCode;//保存验证码 这Session是在前台调用的。
        return validateCode;// 返回验证码
    }

public static bool installFont(string FontFileName, string FontName) 

string WinFontDir = System.Environment.GetEnvironmentVariable("WINDIR")

  fontStyle -= FontStyle.Regular;
  fontStyle |= FontStyle.Bold;

澳门新浦京娱乐场网站NET中登陆验证码的生成和输入验证码的验证,读取字体。        checkCode = Guid.NewGuid().ToString().Substring(0, 4);

    private void DisturbBitmap(Bitmap bitmap)//图像背景
    {
        Random random = new Random();//通过随机数生成
        for (int i = 0; i < bitmap.Width; i )//通过循环嵌套,逐个像素点生成
        {
            for (int j = 0; j < bitmap.Height; j )
            {
                if (random.Next(90) <= this.fineness)
                    bitmap.SetPixel(i, j, Color.LightGray);
            }
        }
    }

  • "\fonts"; 
    //string FontFileName = "DS-Digital Bold Italic.TTF"; 
    //string FontName = "DS-Digital Bold Italic"; 
    int Ret; 
    int Res; 
    string FontPath; 
    //const int WM_澳门新浦京娱乐场网站NET中登陆验证码的生成和输入验证码的验证,读取字体。FONTCHANGE = 0x001D; 
    //const int HWND_BROADCAST = 0xffff; 
    FontPath = WinFontDir "\" FontFileName; 
    try 

    if (!File.Exists(FontPath)) 

    File.Copy(System.Windows.Forms.Application.StartupPath "\font\"
  • FontFileName, FontPath); //font是程序目录下放字体的文件夹
    Ret = AddFontResource(FontPath); 

 

        //用于客户端校验码比较
        Session["CheckCode"] = checkCode;
        return checkCode;
    }

    private void DrewValidateCode(Bitmap bitmap, string validateCode)//绘制验证码图像
    {
        Graphics g = Graphics.FromImage(bitmap);//获取绘制器对象
        Font font = new Font(fontFamily, fontSize, FontStyle.Bold);//设置绘制字体
        g.DrawString(validateCode, font, Brushes.Black, posX, posY);//绘制验证码图像
    }

//Res = SendMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0); 
//WIN7下编译会出错,不清楚什么问题。注释就行了。  
Ret = WriteProfileString("fonts", FontName "(TrueType)", FontFileName); 

}catch(Exception ex) 

MessageBox.Show("[ " FontName " ]字体安装失败!原因:" ex.Message); 
return false; 

return true; 
}

  Font font = new Font(FML, 字体大小, fontStyle, GraphicsUnit.Point);

    //将验证码生成图片显示
    private void CreateCheckCodeImage(string checkCode)
    {
        if (checkCode == null || checkCode.Trim() == String.Empty)
            return;

 

函数的使用: 
fonts.installFont(字体文件, 字体名称)//fonts类名
fonts.installFont("C39P36DmTt.TTF", "C39P36DmTt")

这个我们可以设置字体加粗,斜体,下划线的功能

        System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
        Graphics g = Graphics.FromImage(image);

二:登陆时验证验证码的正确性

2.调用字体文件
//程序直接调用字体文件,不用安装到系统字库中。
设置字体对象:
String ls_appPath = System.Windows.Forms.Application.StartupPath "\font\";//font是程序目录下放字体的文件夹
String fontFile1 = ls_appPath "C39P36DmTt.TTF";
String fontFile2 = ls_appPath "GWGLYPTT.TTF";
......
pfc.AddFontFile(fontFile1);//字体文件的路径
澳门新浦京娱乐场网站,pfc.AddFontFile(fontFile2);//字体文件的路径
........
Font myFont1 = new Font(pfc.Families[0], 41, FontStyle.Regular, GraphicsUnit.Point, 0);//myFont1就是你创建的字体对象
Font myFont2 = new Font(pfc.Families1], 31, FontStyle.Bold | FontStyle.Regular); 

 

        try
        {
            //生成随机生成器 
            Random random = new Random();

  if (TextBox1.Text.ToUpper().Equals(Session["vcode"] ""))【Session["vcode"]为生成验证码时保存的session值】

使用字体:
label1.Font = myFont1;

Color color = ColorTranslator.FromHtml("#ff0000");  //设置字体颜色

            //清空图片背景色 
            g.Clear(Color.White);

  

         
            /// 随机取一个字体
            int fontIndex = random.Next(0, FontItems.Length);
            FontStyle fontStyle = GetFontStyle(random.Next(0, 2));
            Font font = new Font(FontItems[fontIndex], 12, fontStyle);

Bitmap image = new Bitmap(width, height);

Graphics g = Graphics.FromImage(image);


//这里设置图片质量
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.CompositingQuality = CompositingQuality.AssumeLinear;
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;


RectangleF rect = new RectangleF(1, 1, width, height);

SolidBrush brush = new SolidBrush(color);//绘制图片

g.DrawString("这里要生成的文字", font, brush, rect);
brush.Dispose();



MemoryStream msBG = new MemoryStream();

            /// 随机取一个笔刷
            int brushIndex = random.Next(0, BrushItems.Length);
            Brush brush = BrushItems[brushIndex];
            g.DrawString(checkCode, font, brush, 2, 2);

  //保存图片

            //画图片的前景噪音点 
            for (int i = 0; i < 30; i )
            {
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);
                image.SetPixel(x, y, Color.FromArgb(random.Next()));
            }

image.Save(msBG, ImageFormat.Png);

            //画图片的边框线 
            g.DrawRectangle(BorderColor, 0, 0, image.Width - 1, image.Height - 1);

 

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            Response.ClearContent();
            Response.ContentType = "image/Gif";
            Response.BinaryWrite(ms.ToArray());
        }
        finally
        {
            g.Dispose();
            image.Dispose();
        }

最后不要忘了释放资源

    }
    /**/
    /// <summary>
    /// 取一个字体的样式
    /// </summary>
    /// <param name="index"></param>
    /// <returns></returns>
    private FontStyle GetFontStyle(int index)
    {
        switch (index)
        {
            case 0:
                return FontStyle.Bold;
            case 1:
                return FontStyle.Italic;
            default:
                return FontStyle.Regular;
        }
    }
}

FML.Dispose();
font.Dispose();
g.Dispose();
image.Dispose();

return File(msBG.ToArray(), "image/png");

  

具体的demo演示大家可以去我网站上查看  

 

本文由澳门新浦京娱乐场网站发布于www.146.net,转载请注明出处:澳门新浦京娱乐场网站NET中登陆验证码的生成和