生成验证码

作者:追风剑情 发布于:2015-10-21 10:22 分类:C#


using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace BitmapTest
{
    class Program
    {
        static void Main(string[] args)
        {
            VerifyCode verifyCode = new VerifyCode();
            verifyCode.Generate();
            verifyCode.Save();
        }
    }

    /// <summary>
    /// 验证码类
    /// </summary>
    public class VerifyCode
    {
        public Bitmap bitmap { private set; get; }
        public string code { private set; get; }

        private Random random = new Random();
        private string fontFamily = "Verdana";
        private List<char> chars = new List<char>();

        public VerifyCode()
        {
            //把A到Z放到列表中
            for (int c = 65; c <= 90; c++)
                chars.Add((char)c);
        }

        //生成验证码图片
        public void Generate()
        {
            Bitmap tmp = new Bitmap(80, 30, PixelFormat.Format32bppArgb);
            Graphics g = Graphics.FromImage(tmp);
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.Clear(Color.DarkGray);
            Font font = new Font(fontFamily, 16, FontStyle.Strikeout);
            SolidBrush brush = new SolidBrush(Color.White);
            StringFormat format = new StringFormat(StringFormatFlags.NoClip);
            format.Alignment = StringAlignment.Near;
            format.LineAlignment = StringAlignment.Center;
            RectangleF rect = new RectangleF(0, 0, tmp.Width, tmp.Height);
            code = "";
            //随机显示5个字母
            for (int i = 0; i < 5; i++)
            {
                //字母位置
                if (i == 0)
                    g.TranslateTransform(3, 0);
                else
                    g.TranslateTransform(13, 0);
                //字母随机旋转
                g.RotateTransform(-4 + random.Next(8));
                //随机字母
                string c = chars[random.Next(chars.Count)].ToString();
                g.DrawString(c, font, brush, rect, format);
                code += c;
            }

            g.ResetTransform();
            AddBackgroundNoisePoint(tmp, g);

            bitmap = tmp;
        }

        //保存验证码图片
        public void Save()
        {
            if (null != bitmap)
                bitmap.Save("VerifyCode.png", ImageFormat.Png);
        }

        //增加噪点
        private void AddBackgroundNoisePoint(Bitmap bmp, Graphics g)
        {
            Random random = new Random();
            using (Pen objPen = new Pen(Color.Azure, 0))
            {
                for (int i = 0; i < bmp.Width; i++)
                {
                    g.DrawRectangle(objPen, random.Next(bmp.Width), random.Next(bmp.Height), 1, 1);
                }
            }
        }
    }
}


效果

VerifyCode.jpg

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号