Unity生成驗證碼圖片C#

一、導入dll庫

??System.Drawing.dll

二、新建一個C#腳本文件

??VerificationCode.cs

using System;
using System.Drawing;
using System.Security.Cryptography;
using System.Drawing.Imaging;
using Random = System.Random;
using UnityEngine;
using System.IO;
/// <summary>
/// 用于創(chuàng)建驗證碼圖片
/// 暫時僅支持4位數  如有其它需求  需要進一步修改
/// </summary>
public class VerificationCode {

    private string text = "";
    private Bitmap image;
    private int letterWidth = 30;  //單個字體的寬度范圍
    private int letterHeight = 60; //單個字體的高度范圍
    private static byte[] randb = new byte[4];
    private static RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider();

    /// <summary>
    /// 字體樣式 信息
    /// </summary>
    private System.Drawing.Font[] fonts = {
        new System.Drawing.Font(new FontFamily("Times New Roman"),30 +Next(1),System.Drawing.FontStyle.Regular),
        new System.Drawing.Font(new FontFamily("Georgia"), 25 + Next(1),System.Drawing.FontStyle.Regular),
        new System.Drawing.Font(new FontFamily("Arial"), 35 + Next(1),System.Drawing.FontStyle.Regular),
        new System.Drawing.Font(new FontFamily("Comic Sans MS"), 28 + Next(1),System.Drawing.FontStyle.Regular)
    };

    /// <summary>
    /// 驗證碼
    /// </summary>
    public string Text
    {
        get { return this.text; }
    }

    /// <summary>
    /// 驗證碼圖片
    /// </summary>
    public System.Drawing.Bitmap Image
    {
        get { return this.image; }
    }

    public VerificationCode(int imgWidth, int imgHeight, int length)
    {
        Number(length, false);
        CreateImage(imgWidth, imgHeight);
    }


    /// <summary>
    /// 生成隨機數字
    /// </summary>
    /// <param name="Length">生成長度</param>
    /// <param name="Sleep">是否要在生成前將當前線程阻止以避免重復</param>
    private string Number(int Length, bool Sleep)
    {
        if (Sleep) System.Threading.Thread.Sleep(3);
        string result = "";
        System.Random random = new System.Random();
        for (int i = 0; i < Length; i++)
        {
            result += random.Next(10).ToString();
        }

        this.text = result;
        //Debug.Log("result: " + result);
        return result;
    }

    /// <summary>
    /// 獲得下一個隨機數
    /// </summary>
    /// <param name="max">最大值</param>
    private static int Next(int max)
    {
        rand.GetBytes(randb);
        int value = BitConverter.ToInt32(randb, 0);
        value = value % (max + 1);
        if (value < 0) value = -value;
        return value;
    }

    /// <summary>
    /// 獲得下一個隨機數
    /// </summary>
    /// <param name="min">最小值</param>
    /// <param name="max">最大值</param>
    private static int Next(int min, int max)
    {
        int value = Next(max - min) + min;
        return value;
    }


    /// <summary>
    /// 繪制驗證碼
    /// </summary>
    private void CreateImage(int imgWidth, int imgHeight)
    {
        image = new Bitmap(imgWidth, imgHeight);
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
        //畫白色背景
        g.Clear(System.Drawing.Color.White);

        //畫三條 擾亂視野的線
        for (int i = 0; i < 2; i++)
        {
            int x1 = Next(imgWidth / 2);
            int x2 = Next(imgWidth/2, imgWidth - 1);
            int y1 = Next(imgHeight / 2);
            int y2 = Next(imgHeight / 2, imgHeight - 1);
            g.DrawLine(new Pen(GetRandomColor()), x1, y1, x2, y2);
        }

        int _x = 0, _y = -30;
        for (int int_index = 0; int_index < this.text.Length; int_index++)
        {
            //隨機字符的左邊位置
            _x += Next(10, 30); //x坐標 累加
            _y = Next(5, 10);//y坐標 在一個范圍內 隨機
            string str_char = this.text.Substring(int_index, 1);
            str_char = Next(1) == 1 ? str_char.ToLower() : str_char.ToUpper();
            Brush newBrush = new SolidBrush(GetRandomColor());
            Point thePos = new Point(_x, _y);
            Debug.Log("index: "+int_index+"    x: "+_x+"    y: "+_y);
            g.DrawString(str_char, fonts[Next(fonts.Length - 1)], newBrush, thePos);
        }
        for (int i = 0; i < 10; i++)
        {
            int x = Next(image.Width - 1);
            int y = Next(image.Height - 1);
            image.SetPixel(x, y, System.Drawing.Color.FromArgb(Next(0, 255), Next(0, 255), Next(0, 255)));
        }
        //image = TwistImage(image, true, Next(1, 3), Next(4, 6));
        //g.DrawRectangle(new Pen(System.Drawing.Color.LightGray, 5), 0, 0, 150 - 1, (letterHeight - 1));
    }

    /// <summary>
    /// 字體隨機顏色
    /// </summary>
    public System.Drawing.Color GetRandomColor()
    {
        System.Random RandomNum_First = new System.Random((int)DateTime.Now.Ticks);
        System.Threading.Thread.Sleep(RandomNum_First.Next(50));
        System.Random RandomNum_Sencond = new System.Random((int)DateTime.Now.Ticks);
        int int_Red = RandomNum_First.Next(180);
        int int_Green = RandomNum_Sencond.Next(180);
        int int_Blue = (int_Red + int_Green > 300) ? 0 : 400 - int_Red - int_Green;
        int_Blue = (int_Blue > 255) ? 255 : int_Blue;
        return System.Drawing.Color.FromArgb(int_Red, int_Green, int_Blue);
    }

    /// <summary>
    /// 將Image 轉為 Texture
    /// </summary>
    /// <param name="im"></param>
    /// <returns></returns>
    public static Texture2D Image2Texture(System.Drawing.Image im)
    {
        if (im == null)
        {
            return new Texture2D(4, 4);
        }

        //Memory stream to store the bitmap data.
        MemoryStream ms = new MemoryStream();

        //Save to that memory stream.
        im.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

        //Go to the beginning of the memory stream.
        ms.Seek(0, SeekOrigin.Begin);
        //make a new Texture2D
        Texture2D tex = new Texture2D(im.Width, im.Height);

        tex.LoadImage(ms.ToArray());

        //Close the stream.
        ms.Close();
        im.Dispose();
        ms = null;
        //
        return tex;
    }

    /*產生驗證碼*/
    public string CreateCode(int codeLength)
    {
        string so = "1,2,3,4,5,6,7,8,9,0,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
        string[] strArr = so.Split(',');
        string code = "";
        Random rand = new Random();
        for (int i = 0; i < codeLength; i++)
        {
            code += strArr[rand.Next(0, strArr.Length)];
        }
        return code;
    }
}

三、調用

 /// <summary>
    /// 顯示圖片驗證碼
    /// </summary>
    /// <param name="img">顯示驗證碼的image組件</param>
    /// <param name="imgWidth">圖片寬度,150</param>
    /// <param name="imgHeight">圖片高度, 60</param>
    /// <param name="length">字符長度,一般為4</param>
    /// <returns>驗證碼字符串</returns>
    private string ShowVerificationCode(Image img, int imgWidth, int imgHeight, int length)
    {
        VerificationCode vCode = new VerificationCode(imgWidth, imgHeight, length);
        Texture2D texture = VerificationCode.Image2Texture(vCode.Image);
        img.sprite = Sprite.Create(texture, new Rect(0, 0, imgWidth, imgHeight), new Vector2(0.5f, 0.5f), 125);
        return vCode.Text;
    }

四、運行結果

五、如果你發(fā)現(xiàn)圖片大小和你想要的不一樣,請繼續(xù)看

? 1.通過構造函數傳圖片的寬,高,驗證碼的長度;
構造函數
? 2.我使用的寬高比為150*60,字符長度為4

??如果不適合你要的size,你可能需要修改以下幾個地方:
字符長寬&字體大小
字符的起始坐標

??生成制定長度隨機數字:
用于生成數字驗證碼
??生成指定長度,數字字母隨機
用于生成數字字母驗證碼
??Image轉Texture2D代碼:
Bitmap2Texture2D
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 一、Unity簡介 1. Unity界面 Shift + Space : 放大界面 Scene界面按鈕渲染模式2D...
    MYves閱讀 8,363評論 0 22
  • 第一、在簡書列出自己2017年的夢想清單,對應下面的每一個欄目寫三個目標: 第二、列出自己認為最喜歡做但是又覺得沒...
    水水張閱讀 156評論 3 3
  • 1.總述 使用jps命令可以列出目標系統(tǒng)上運行的JVM進程。如果不指定任何選項,該命令將列出本地JVM進程ID和主...
    Hypercube閱讀 1,724評論 0 2
  • 姓名:黃福強 公司:上海金橋高中壓閥門廠有限公司 六項精進第397期 學員【日精進打卡第67天】 六項精進第411...
    皓月灬朗星閱讀 137評論 0 0
  • “是嗎,俗話說,‘愿天下有情人終成眷屬’,可是,又有多少癡男怨女做到了?”墨清弦苦笑著。 “如果,你喜歡一個人,但...
    curry_19b7閱讀 245評論 0 0