1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| public class ValidateCodeCreator { public string CreateCode(int codeLength) { string so = "1,2,3,4,5,6,7,8,9,0,a,b,c,d,e,f,g,h,i,j,k,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z"; string[] strArr = so.Split(','); string code = ""; Random rand = new Random(); for (int i = 0; i < codeLength; i++) { code += strArr[rand.Next(0, strArr.Length)]; } return code; } public byte[] CreateCodeImage(string code) { Bitmap image = new Bitmap(code.Length * 22, 30); Graphics g = Graphics.FromImage(image); Random r = new Random(); try { WebColorConverter ww = new WebColorConverter(); string[] backgroundcolor = { "#F8F8FF", "#BBFFFF", "#E6E6FA", "#CAE1FF", "#FFFACD", "#B0E2FF" }; g.Clear((Color)ww.ConvertFromString(backgroundcolor[r.Next(0,5)])); string[] fonts = { "黑体", "微软雅黑", "隶书", "楷体" }; Color[] codecolors = { Color.Red, Color.Black, Color.Blue, Color.Purple, Color.DarkGoldenrod, Color.Magenta, Color.Khaki }; Color[] linecolors = { Color.Green, Color.DarkGreen, Color.SeaGreen, Color.DarkSlateBlue }; for (int i = 0; i < code.Length; i++) { Point p = new Point(i * 20, 0); g.DrawString(code[i].ToString(), new Font(fonts[r.Next(0,3)], 20, FontStyle.Italic), new SolidBrush(codecolors[r.Next(0,6)]), p); } int linecolormk = r.Next(0, 3); for (int j = 0; j < 12; j++) { Point p1 = new Point(r.Next(0, image.Width), r.Next(image.Height)); Point p2 = new Point(r.Next(0, image.Width), r.Next(0, image.Height)); g.DrawLine(new Pen(linecolors[linecolormk]), p1, p2); } for (int i = 0; i < 100; i++) { Point p1 = new Point(r.Next(0, image.Width), r.Next(image.Height)); Point p2 = new Point(r.Next(0, image.Width), r.Next(0, image.Height)); image.SetPixel(p1.X, p1.Y, Color.Black); } MemoryStream ms = new MemoryStream(); image.Save(ms, ImageFormat.Gif); return ms.ToArray(); } finally { g.Dispose(); image.Dispose(); } }
|