Random picture generator production method to share

  • 2020-10-23 20:56:49
  • OfStack


/// <summary>
    /// PicHandler1  Summary description of 
    /// </summary>
    public class PicHandler1 : IHttpHandler, IRequiresSessionState
    {
        private string mCheckNo = string.Empty;
        protected ImgBuilder _ImgBuilder = new ImgBuilder();
        protected VryImgGen _ImgBuilderNew = new VryImgGen();
        private string _text = string.Empty;
        private string _font = " Song typeface ";
        private int _fontSize = 8;
        private int _padding = 2;
        public void ProcessRequest(HttpContext context)
        {
            mCheckNo = DisCheckNo();
            context.Session["CheckCode"] = mCheckNo;
            this._ImgBuilder.FontSize = this._fontSize;
            this._ImgBuilder.Padding = this._padding;
            if (!string.IsNullOrEmpty(this._font))
            {
                this._ImgBuilder.Fonts = new string[] { this._font };
            }
            this._ImgBuilderNew.ChaosWight = 40;
            this._ImgBuilderNew.FontSize = 25;
            this._ImgBuilderNew.Padding = 3;
            System.Drawing.Bitmap image =
             this._ImgBuilderNew.CreateImage(mCheckNo);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            context.Response.ClearContent();
            context.Response.ContentType = "image/Jpeg";
            context.Response.BinaryWrite(ms.ToArray());
            context.Session["CheckCode"] = mCheckNo.ToString(); // If it's not implemented IRequiresSessionState , an error will occur and the image cannot be generated 
            context.Response.End();
        }
        // Verification code generation 
        protected string DisCheckNo()
        {
            string hash = HashCode.GetNext();
            string CheckNo = string.Empty;
            Random rd = new Random(DateTime.Now.Millisecond);
            for (int i = 0; i < 6; i++)
            {
                CheckNo += hash.Substring(rd.Next(1, hash.Length - 1), 1);
            }
            CheckNo = CheckNo.Replace("0", rd.Next(1, 9).ToString());
            CheckNo = CheckNo.Replace("o", rd.Next(1, 9).ToString());
            CheckNo = CheckNo.Replace("O", rd.Next(1, 9).ToString());
            return CheckNo;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }


A class is called


using System;
using System.Drawing;
using System.Text;
/// <summary>
/// VryImgGen  Summary description of 
/// </summary>
public class VryImgGen
{
    public static string ChineseChars = String.Empty;
    /// <summary>
    ///  English and Numbers string 
    /// </summary>
    protected static readonly string EnglishOrNumChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public VryImgGen()
    {
        rnd = new Random(unchecked((int)DateTime.Now.Ticks));
    }
    /// <summary>
    ///  Global random number generator 
    /// </summary>
    private Random rnd;
    int length = 5;
    /// <summary>
    ///  Captcha length ( The default 6 The length of a captcha )
    /// </summary>
    public int Length
    {
        get { return length; }
        set { length = value; }
    }
    int fontSize = 20;
    /// <summary>
    ///  Captcha font size ( To display distortion effects, default 30 Pixels, you can modify )
    /// </summary>
    public int FontSize
    {
        get { return fontSize; }
        set { fontSize = value; }
    }
    int padding = 4;
    /// <summary>
    ///  Border to fill ( The default 4 pixel )
    /// </summary>
    public int Padding
    {
        get { return padding; }
        set { padding = value; }
    }
    bool chaos = true;
    /// <summary>
    ///  Whether output dry point ( The default output )
    /// </summary>
    public bool Chaos
    {
        get { return chaos; }
        set { chaos = value; }
    }
    Color chaosColor = Color.LightGray;
    /// <summary>
    ///  Output the color of the dryness point ( The default gray )
    /// </summary>
    public Color ChaosColor
    {
        get { return chaosColor; }
        set { chaosColor = value; }
    }
    int chaosWight = 1;
    /// <summary>
    ///  Output dryness point concentration 
    /// </summary>
    public int ChaosWight
    {
        get { return chaosWight; }
        set { chaosWight = value; }
    }
    Color backgroundColor = Color.White;
    /// <summary>
    ///  Customize the background color ( The default white )
    /// </summary>
    public Color BackgroundColor
    {
        get { return backgroundColor; }
        set { backgroundColor = value; }
    }
    Color[] colors = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
    /// <summary>
    ///  Custom random color array 
    /// </summary>
    public Color[] Colors
    {
        get { return colors; }
        set { colors = value; }
    }
    string[] fonts = { "Arial", "Georgia" };
    /// <summary>
    ///  Custom font array 
    /// </summary>
    public string[] Fonts
    {
        get { return fonts; }
        set { fonts = value; }
    }
    #region  Creates a waveform filter effect 
    private const double PI = 3.1415926535897932384626433832795;
    private const double PI2 = 6.283185307179586476925286766559;
    /// <summary>
    ///  Sine curve Wave Distorted picture ( Edit By 51aspx.com ) 
    /// </summary>
    /// <param name="srcBmp"> Image path </param>
    /// <param name="bXDir"> If distorted, select as True</param>
    /// <param name="nMultValue"> The larger the amplitude multiples of the waveform, the higher the degree of distortion, 1 As for the 3</param>
    /// <param name="dPhase"> Initial phase of waveform, value interval [0-2*PI)</param>
    /// <returns></returns>
    public System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
    {
        System.Drawing.Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);
        //  Fill the bitmap background with white 
        System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(destBmp);
        graph.FillRectangle(new SolidBrush(System.Drawing.Color.White), 0, 0, destBmp.Width, destBmp.Height);
        graph.Dispose();
        double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width;
        for (int i = 0; i < destBmp.Width; i++)
        {
            for (int j = 0; j < destBmp.Height; j++)
            {
                double dx = 0;
                dx = bXDir ? (PI2 * (double)j) / dBaseAxisLen : (PI2 * (double)i) / dBaseAxisLen;
                dx += dPhase;
                double dy = Math.Sin(dx);
                //  Gets the color of the current point 
                int nOldX = 0, nOldY = 0;
                nOldX = bXDir ? i + (int)(dy * dMultValue) : i;
                nOldY = bXDir ? j : j + (int)(dy * dMultValue);
                System.Drawing.Color color = srcBmp.GetPixel(i, j);
                if (nOldX >= 0 && nOldX < destBmp.Width
                 && nOldY >= 0 && nOldY < destBmp.Height)
                {
                    destBmp.SetPixel(nOldX, nOldY, color);
                }
            }
        }
        return destBmp;
    }
 
    #endregion
    /// <summary>
    ///  Generate check code images 
    /// </summary>
    /// <param name="code"> Verification code </param>
    /// <returns></returns>
    public Bitmap CreateImage(string code)
    {
        int fSize = FontSize;
        int fWidth = fSize + Padding;
        int imageWidth = (int)(code.Length * fWidth) + 4 + Padding * 2;
        int imageHeight = fSize * 2 + Padding * 2;
        System.Drawing.Bitmap image = new System.Drawing.Bitmap(imageWidth - 10, imageHeight - 10);
        Graphics g = Graphics.FromImage(image);
        g.Clear(BackgroundColor);
        // Add randomly generated dry points to the background 
        if (this.Chaos)
        {
            Pen pen = new Pen(ChaosColor, 0);
            int c = ChaosWight * 10;
            for (int i = 0; i < c; i++)
            {
                int x = rnd.Next(image.Width);
                int y = rnd.Next(image.Height);
                g.DrawRectangle(pen, x, y, 1, 1);
            }
        }
        int left = 0, top = 0, top1 = 1, top2 = 1;
        int n1 = (imageHeight - FontSize - Padding * 2);
        int n2 = n1 / 4;
        top1 = n2;
        top2 = n2 * 2;
        Font f;
        Brush b;
        int cindex, findex;
        // Captcha characters for random fonts and colors 
        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);
        }
        // draw 1 A border   Border color is Color.Gainsboro
        g.DrawRectangle(new Pen(Color.Gainsboro, 0), 0, 0, image.Width - 1, image.Height - 1);
        g.Dispose();
        // Generate waveform ( Add By 51aspx.com ) 
        image = TwistImage(image, true, 8, 4);
        return image;
    }
    /// <summary>
    ///  Generate random character codes 
    /// </summary>
    /// <param name="codeLen"> String length </param>
    /// <param name="zhCharsCount"> Chinese character count </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>
    ///  Generate default length 5 Is a random character code 
    /// </summary>
    /// <returns></returns>
    public string CreateVerifyCode()
    {
        return CreateVerifyCode(Length, 0);
    }
    /// <summary>
    ///  Generate English or numeric characters 
    /// </summary>
    /// <returns></returns>
    protected char CreateEnOrNumChar()
    {
        return EnglishOrNumChars[rnd.Next(0, EnglishOrNumChars.Length)];
    }
    /// <summary>
    ///  Generate Chinese character 
    /// </summary>
    /// <returns></returns>
    protected char CreateZhChar()
    {
        // If a Chinese character set is provided, query the Chinese character set to select a Chinese character 
        if (ChineseChars.Length > 0)
        {
            return ChineseChars[rnd.Next(0, ChineseChars.Length)];
        }
        // If the Chinese character set is not provided, the GB2312 Simplified Chinese Code Table code rules for The construction of Chinese characters 
        else
        {
            byte[] bytes = new byte[2];
            // The first 1 Two byte value in 0xb0, 0xf7 between 
            bytes[0] = (byte)rnd.Next(0xb0, 0xf8);
            // The first 2 Two byte value in 0xa1, 0xfe between 
            bytes[1] = (byte)rnd.Next(0xa1, 0xff);
            // Chinese characters are decoded from a byte array encoded in Chinese characters 
            string str1 = Encoding.GetEncoding("gb2312").GetString(bytes);
            return str1[0];
        }
    }
}


Related articles: