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>
/// 用于创建验证码图片
/// 暂时仅支持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;
    }

四、运行结果

五、如果你发现图片大小和你想要的不一样,请继续看

  1.通过构造函数传图片的宽,高,验证码的长度;
构造函数
  2.我使用的宽高比为150*60,字符长度为4

  如果不适合你要的size,你可能需要修改以下几个地方:
字符长宽&字体大小
字符的起始坐标

  生成制定长度随机数字:
用于生成数字验证码
  生成指定长度,数字字母随机
用于生成数字字母验证码
  Image转Texture2D代码:
Bitmap2Texture2D
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 229,885评论 6 541
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 99,312评论 3 429
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 177,993评论 0 383
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 63,667评论 1 317
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 72,410评论 6 411
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 55,778评论 1 328
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 43,775评论 3 446
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 42,955评论 0 289
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 49,521评论 1 335
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 41,266评论 3 358
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 43,468评论 1 374
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 38,998评论 5 363
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 44,696评论 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 35,095评论 0 28
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 36,385评论 1 294
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 52,193评论 3 398
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 48,431评论 2 378

推荐阅读更多精彩内容

  • 一、Unity简介 1. Unity界面 Shift + Space : 放大界面 Scene界面按钮渲染模式2D...
    MYves阅读 8,352评论 0 22
  • 第一、在简书列出自己2017年的梦想清单,对应下面的每一个栏目写三个目标: 第二、列出自己认为最喜欢做但是又觉得没...
    水水张阅读 156评论 3 3
  • 1.总述 使用jps命令可以列出目标系统上运行的JVM进程。如果不指定任何选项,该命令将列出本地JVM进程ID和主...
    Hypercube阅读 1,716评论 0 2
  • 姓名:黄福强 公司:上海金桥高中压阀门厂有限公司 六项精进第397期 学员【日精进打卡第67天】 六项精进第411...
    皓月灬朗星阅读 137评论 0 0
  • “是吗,俗话说,‘愿天下有情人终成眷属’,可是,又有多少痴男怨女做到了?”墨清弦苦笑着。 “如果,你喜欢一个人,但...
    curry_19b7阅读 245评论 0 0