WEB服务端方法:
[WebMethod]
public byte[] GenerateVerifyImage(int nLen, ref string strKey)
{
int nBmpWidth = 13 * nLen + 5;
int nBmpHeight = 25;
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(nBmpWidth, nBmpHeight);
int nRed, nGreen, nBlue; // 背景的三元色
System.Random rd = new Random((int)System.DateTime.Now.Ticks);
nRed = rd.Next(255) % 128 + 128;
nGreen = rd.Next(255) % 128 + 128;
nBlue = rd.Next(255) % 128 + 128;
System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(bmp);
graph.FillRectangle(new SolidBrush(System.Drawing.Color.FromArgb(nRed, nGreen, nBlue))
, 0
, 0
, nBmpWidth
, nBmpHeight);
int nLines = 3;
System.Drawing.Pen pen = new System.Drawing.Pen(System.Drawing.Color.FromArgb(nRed - 17, nGreen - 17, nBlue - 17), 2);
for (int a = 0; a < nLines; a++)
{
int x1 = rd.Next() % nBmpWidth;
int y1 = rd.Next() % nBmpHeight;
int x2 = rd.Next() % nBmpWidth;
int y2 = rd.Next() % nBmpHeight;
graph.DrawLine(pen, x1, y1, x2, y2);
}
string strCode = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string strResult = "";
for (int i = 0; i < nLen; i++)
{
int x = (i * 13 + rd.Next(3));
int y = rd.Next(4) + 1;
System.Drawing.Font font = new System.Drawing.Font("Courier New",
12 + rd.Next() % 4,
System.Drawing.FontStyle.Bold);
char c = strCode[rd.Next(strCode.Length)]; // 随机获取字符
strResult += c.ToString();
graph.DrawString(c.ToString(),
font,
new SolidBrush(System.Drawing.Color.FromArgb(nRed - 60 + y * 3, nGreen - 60 + y * 3, nBlue - 40 + y * 3)),
x,
y);
}
System.IO.MemoryStream bstream = new System.IO.MemoryStream();
bmp.Save(bstream, System.Drawing.Imaging.ImageFormat.Jpeg);
bmp.Dispose();
graph.Dispose();
strKey = strResult;
byte[] byteReturn = bstream.ToArray();
bstream.Close();
return byteReturn;
}
客户端应用:
string code1 = GenerateCheckCode();//产生随机字符串方法如下:
ValidateCodeService.ValidateCodeWebServiceSoapClient vws = new ValidateCodeService.ValidateCodeWebServiceSoapClient();
byte[] data = vws.enValidateByte(code1);
MemoryStream ms = new MemoryStream(data);
Image img = Image.FromStream(ms);//将字符流转化为图片,用于显示在picturebox控件中;
pictureBox2.Image = img;
private string GenerateCheckCode()
{
int number;
char code;
string checkCode = String.Empty;
Random random = new Random();
for (int i = 0; i < 4; i++)
{ number = random.Next();
if (number % 2 == 0)
code = (char)('0' + (char)(number % 10));
else
code = (char)('A' + (char)(number % 26));
checkCode += code.ToString();
}
return checkCode;
}
标签:WEB,Service,int,验证码,System,rd,new,Next,Drawing From: https://blog.51cto.com/u_15917617/5953265