先看这个demo的解决方案图 Entity是实体,里面有验证码的实体
private string contentType = "image/pjpeg"; private ImageFormat imageFormat = ImageFormat.Jpeg; public Bitmap Image { get; set; } public string ContentType { get { return contentType; } set { contentType = value; } } public ImageFormat ImageFormat { get { return imageFormat; } set { imageFormat = value; } }
public interface IVerifyImage { VerifyImageInfo GenerateImage(string code, int width, int height, Color bgcolor, int textcolor); }
provider类是一个抽象工厂代码为
private static Hashtable _instance = new Hashtable(); private static object lockHelper = new object(); //通过接口和反射结合配置文件信息来做整站多验证码技术 public static IVerifyImage GetInstance(string assemlyName) { if (!_instance.Contains(assemlyName)) { lock (lockHelper) { if (!_instance.ContainsKey(assemlyName)) { IVerifyImage p = null; try { p = (IVerifyImage)Activator.CreateInstance(Type.GetType(string.Format("Plugin.VerifyImage.{0}.VerifyImage,Plugin.VerifyImage.{0}", assemlyName), false, true)); } catch { p = new Plugin.VerifyImage.JpegImage.VerifyImage(); } _instance.Add(assemlyName, p); } } } return (IVerifyImage)_instance[assemlyName]; }
protected override void OnInit(EventArgs e) { base.OnInit(e); string verifyAssembly = "JpegImage";//此处信息可从配置文件获得 string bgColor = "";//Request.QueryString["bgcolor"].Trim(); int fontColor = 1; //StrToInt(Request.QueryString["fontcolor"].Trim(), 1); string[] bgcolorArray = bgColor.Split(','); Color bg = Color.White; if (bgcolorArray.Length == 1 && bgColor != string.Empty) { bg = ToColor(bgColor); } else if (bgcolorArray.Length == 3 && IsNumericArray(bgcolorArray)) { bg = Color.FromArgb(StrToInt(bgcolorArray[0], 255), StrToInt(bgcolorArray[1], 255), StrToInt(bgcolorArray[2], 255)); } VerifyImageInfo verifyimg = Plugin.VerifyImage.VerifyImageProvider.GetInstance(verifyAssembly).GenerateImage(CreateAuthStr(5, false), 120, 60, bg, fontColor); Bitmap image = verifyimg.Image; System.Web.HttpContext.Current.Response.ContentType = verifyimg.ContentType; //MemoryStream ms = new MemoryStream(); image.Save(this.Response.OutputStream, verifyimg.ImageFormat); }
<script type="text/javascript"> document.getElementById('vcodeimg').src='/tools/VerifyImagePage.aspx?id=4&time=' + Math.random(); </script>
源代码下载vertify.rar