我在 SO 和 MSDN 中找到了这些用于创建 CAPTCHA 图像的代码:
private Image DrawText(String text, Font font, Color textColor, Color backColor)
{
//first, create a dummy bitmap just to get a graphics object
Image img = new Bitmap(1, 1);
Graphics drawing = Graphics.FromImage(img);
//measure the string to see how big the image needs to be
SizeF textSize = drawing.MeasureString(text, font);
//free up the dummy image and old graphics object
img.Dispose();
drawing.Dispose();
//create a new image of the right size
Bitmap b = new Bitmap((int)textSize.Width, (int)textSize.Height);
int distortion = 2;
Bitmap copy = b;
for (int y = 0; y < textSize.Height; y++)
{
for (int x = 0; x < textSize.Width; x++)
{
int newX = (int)(x + (distortion * Math.Sin(Math.PI * y / 64.0)));
int newY = (int)(y + (distortion * Math.Cos(Math.PI * x / 64.0)));
if (newX < 0 || newX >= textSize.Width) newX = 0;
if (newY < 0 || newY >= textSize.Height) newY = 0;
b.SetPixel(x, y, copy.GetPixel(newX, newY));
}
}
img = b;
drawing = Graphics.FromImage(img);
//paint the background
drawing.Clear(backColor);
//create a brush for the text
Brush textBrush = new SolidBrush(textColor);
drawing.DrawString(text, font, textBrush, 0, 0);
drawing.Save();
textBrush.Dispose();
drawing.Dispose();
return img;
}
我还使用此代码将图像输出到浏览器:
Image image = DrawText("3", new Font("Thahoma", 20), Color.Black, Color.White);
context.Response.ContentType = "image/png";
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
ms.WriteTo(context.Response.OutputStream);
}
但是此代码不会输出图像而没有任何错误;当我清除那些for
s 时,它会显示图像。我的 Web 应用程序将在私有 Intranet 中运行,所以不推荐 reCAPTCHA!