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

复制代码 代码如下:


/// <summary>
    /// PicHandler1 的摘要说明
    /// </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 = "宋体";
        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(); //如果没有实现IRequiresSessionState,则这里会出错,也无法生成图片
            context.Response.End();
        }

//验证码生成
        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;
            }
        }
    }


调用的类

复制代码 代码如下:


using System;
using System.Drawing;
using System.Text;

/// <summary>
/// VryImgGen 的摘要说明
/// </summary>
public class VryImgGen
{
    public static string ChineseChars = String.Empty;

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

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