随机图片生成器制作方法分享(4)

//随机字体和颜色的验证码字符
        for (int i = 0; i < code.Length; i++)
        {
            cindex = rnd.Next(Colors.Length - 1);
            findex = rnd.Next(Fonts.Length - 1);

f = new System.Drawing.Font(Fonts[findex], fSize, System.Drawing.FontStyle.Bold);
            b = new System.Drawing.SolidBrush(Colors[cindex]);

if (i % 2 == 1)
            {
                top = top2;
            }
            else
            {
                top = top1;
            }

left = i * fWidth;

g.DrawString(code.Substring(i, 1), f, b, left, top);
        }

//画一个边框 边框颜色为Color.Gainsboro
        g.DrawRectangle(new Pen(Color.Gainsboro, 0), 0, 0, image.Width - 1, image.Height - 1);
        g.Dispose();

//产生波形(Add By 51aspx.com)
        image = TwistImage(image, true, 8, 4);

return image;
    }

/// <summary>
    /// 生成随机字符码
    /// </summary>
    /// <param>字符串长度</param>
    /// <param>中文字符数</param>
    /// <returns></returns>
    public string CreateVerifyCode(int codeLen, int zhCharsCount)
    {
        char[] chs = new char[codeLen];

int index;
        for (int i = 0; i < zhCharsCount; i++)
        {
            index = rnd.Next(0, codeLen);
            if (chs[index] == '\0')
                chs[index] = CreateZhChar();
            else
                --i;
        }
        for (int i = 0; i < codeLen; i++)
        {
            if (chs[i] == '\0')
                chs[i] = CreateEnOrNumChar();
        }

return new string(chs, 0, chs.Length);
    }

/// <summary>
    /// 生成默认长度5的随机字符码
    /// </summary>
    /// <returns></returns>
    public string CreateVerifyCode()
    {
        return CreateVerifyCode(Length, 0);
    }

/// <summary>
    /// 生成英文或数字字符
    /// </summary>
    /// <returns></returns>
    protected char CreateEnOrNumChar()
    {
        return EnglishOrNumChars[rnd.Next(0, EnglishOrNumChars.Length)];
    }

/// <summary>
    /// 生成汉字字符
    /// </summary>
    /// <returns></returns>
    protected char CreateZhChar()
    {
        //若提供了汉字集,查询汉字集选取汉字
        if (ChineseChars.Length > 0)
        {
            return ChineseChars[rnd.Next(0, ChineseChars.Length)];
        }
        //若没有提供汉字集,则根据《GB2312简体中文编码表》编码规则构造汉字
        else
        {
            byte[] bytes = new byte[2];

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjgywf.html