1. 程式人生 > >C# 返回圖片驗證碼和返回驗證碼中的字串

C# 返回圖片驗證碼和返回驗證碼中的字串

直接把這個類複製出去就能使用

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;

namespace 生成驗證碼
{
    class CreateImage
    {

        public  Image CrtImage(out string OutPutstr)
        {
            
            Bitmap bmp = new Bitmap(200, 50);
            string str = "";
            try
            {
                Random r = new Random();
                char[] c = { 'A', 'v', 'd', 'Q', 'e', 'E', 'f', 'h', 'u', 'B' };
              
                for (int i = 0; i < 5; i++)
                {
                    int temp = r.Next(0, 10);
                    str += temp;
                    if (i % 2 == 0) str += c[temp];  / /這裡 += 了3個字母
                }
                //圖片中的字串一共有8個字元
                
                //建立畫圖物件
                Graphics gp = Graphics.FromImage(bmp);

                string[] fonts = { "楷體", "宋體", "微軟雅黑", "隸書", "黑體" };
                Color[] color = { Color.Black, Color.Coral, Color.Green, Color.Aqua, Color.Red,Color.Beige,Color.Blue,Color.CadetBlue };

                for (int i = 0; i < str.Length; i++)//在畫布上面打印出多少個字元(應該與字串的長度相等)
                {
                    Point p = new Point(i * 20, i);
                    gp.DrawString(str[i].ToString(), new Font(fonts[r.Next(0, 5)], 20, FontStyle.Bold), new SolidBrush(color[r.Next(0, 8)]), p);

                }

                for (int i = 0; i < 100; i++) //繪製隨機直線(直線不夠多可以將迴圈次數改大點)
                {
                    Point temp1 = new Point(r.Next(0, bmp.Width), r.Next(0, bmp.Width));
                    Point temp2 = new Point(r.Next(0, bmp.Width), r.Next(0, bmp.Width));
                    gp.DrawLine(new Pen(Color.Black), temp1, temp2);
                }

                for (int i = 0; i < 500; i++)//繪製畫素顆粒(畫素顆粒不夠多可以將迴圈次數改大點)
                {

                    Point p = new Point(r.Next(0, bmp.Width), r.Next(0, bmp.Height));
                    bmp.SetPixel(p.X, p.Y, Color.Red);
                }
            }
            catch
            {
                OutPutstr = “”;// 發生異常返回空
              return null;//
            }
            OutPutstr = str;
            return bmp;//將圖片賦值給控制元件(或者直接返回一個圖片物件)
        }
    }
}