Captcha(bool createBuilder, Config config) { // the createBuilder is false when the object has been created from the builder // and true when a public constructor is used instead if (createBuilder) { if (config == null) { throw new ArgumentNullException("config", "Configuration object can't be null"); } new Builder(this) .Background(CreateDefaultBackground(config)) .Keygen(CreateDefaultKeygen(config)) .Drawer(CreateDefaultDrawer(config)) .Filters(CreateDefaultFilters(config)) .Build(); } }
/// <summary> /// Initializes a new instance using configuration. /// </summary> public Captcha(Config config) : this(createBuilder: true, config: config) { }
static IKeygen CreateDefaultKeygen(Config config) { return new Keygen(NumberGenerator.Instance) { KeyLength = config.KeyLength, Alphabet = config.BitmapFont.Alphabet }; }
static IFilter[] CreateDefaultFilters(Config config) { if (config.WavesFilterEnabled) { var random = NumberGenerator.Instance; // 0..2PI phase var xWave = new WavesFilter.Wave(0.15f, 2, random.NextInt(0, 628) / 100f); var bigYWave = new WavesFilter.Wave(0.040f, random.NextInt(6, 8), random.NextInt(0, 628) / 100f); var smallYWave = new WavesFilter.Wave(0.1f, random.NextInt(2, 4), random.NextInt(0, 628) / 100f); return new IFilter[] { new WavesFilter( new WavesFilter.Wave[] { xWave }, new WavesFilter.Wave[] { bigYWave, smallYWave }) }; } else { return new IFilter[0]; } }
static IDrawer CreateDefaultDrawer(Config config) { return new Drawer(NumberGenerator.Instance) { Font = config.BitmapFont, FontColor = config.ForegroundColor, OverlayEnabled = config.OverlayEnabled, OverlayPixels = 0 }; }
static Image CreateDefaultBackground(Config config) { var bg = new Bitmap(config.ImageWidth, config.ImageHeight); using (Graphics graphics = Graphics.FromImage(bg)) using (SolidBrush brush = new SolidBrush(config.BackgroundColor)) { graphics.FillRectangle(brush, 0, 0, config.ImageWidth, config.ImageHeight); } return bg; }
public static Config Parse(object obj) { var config = new Config(); if (obj == null) { throw new ArgumentNullException("obj", "Can't parse null object"); } PropertyInfo[] props = obj.GetType().GetProperties(); foreach (PropertyInfo prop in props) { object val = prop.GetValue(obj, null); string type = prop.PropertyType.FullName; string name = prop.Name.ToLower(); switch (name) { case "keylength": config.keyLength = ParseInt(name, type, val); break; case "width": config.imageWidth = ParseInt(name, type, val); break; case "height": config.imageHeight = ParseInt(name, type, val); break; case "foreground": config.foregroundColor = ParseColor(name, type, val); break; case "background": config.backgroundColor = ParseColor(name, type, val); break; case "overlay": config.overlayEnabled = ParseBool(name, type, val); break; case "waves": config.wavesFilterEnabled = ParseBool(name, type, val); break; case "font": config.fontPath = ParseString(name, type, val); break; } } config.InitValues(); return config; }