c# 生成验证码图片
程序员文章站
2022-10-01 17:32:39
/// /// 生成验证码图片 /// /// public byte[] GetVerifyCode() { int codeW = 80; int codeH = 40; int fontSize = 18; ... ......
/// <summary> /// 生成验证码图片 /// </summary> /// <returns></returns> public byte[] getverifycode() { int codew = 80; int codeh = 40; int fontsize = 18; string chkcode = string.empty; //颜色列表,用于验证码、噪线、噪点 color[] color = { color.black, color.red, color.blue, color.green, color.orange, color.brown, color.brown, color.darkblue }; //字体列表,用于验证码 string[] font = { "times new roman" }; //验证码的字符集,去掉了一些容易混淆的字符 char[] character = { '2', '3', '4', '5', '6', '8', '9', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'r', 's', 't', 'w', 'x', 'y' }; random rnd = new random(); //生成验证码字符串 for (int i = 0; i < 4; i++) { chkcode += character[rnd.next(character.length)]; } //创建画布 bitmap bmp = new bitmap(codew, codeh); graphics g = graphics.fromimage(bmp); g.clear(color.white); //画噪线 for (int i = 0; i < 1; i++) { int x1 = rnd.next(codew); int y1 = rnd.next(codeh); int x2 = rnd.next(codew); int y2 = rnd.next(codeh); color clr = color[rnd.next(color.length)]; g.drawline(new pen(clr), x1, y1, x2, y2); } //画验证码字符串 for (int i = 0; i < chkcode.length; i++) { string fnt = font[rnd.next(font.length)]; font ft = new font(fnt, fontsize); color clr = color[rnd.next(color.length)]; g.drawstring(chkcode[i].tostring(), ft, new solidbrush(clr), (float)i * 18, (float)0); } //将验证码图片写入内存流,并将其以 "image/png" 格式输出 memorystream ms = new memorystream(); try { bmp.save(ms, imageformat.png); return ms.toarray(); } catch (exception) { return null; } finally { g.dispose(); bmp.dispose(); } }