我使用this article创建验证码图像,我将它的代码放在我的WebService中以返回图像' Captcha到客户端(app.js),但我有很多错误。
public class Captcha : System.Web.Services.WebService
{
[WebMethod(EnableSession = true)]
public Bitmap CaptchaImage()
{
bool noisy = true;
var rand = new Random((int)DateTime.Now.Ticks);
//generate new question
int a = rand.Next(10, 99);
int b = rand.Next(0, 9);
var captcha = string.Format("{0} + {1} = ?", a, b);
//store answer
Session["Captcha-1"] = a + b;
//image stream
FileContentResult img = null; //get error for FileContentResult
using (var mem = new MemoryStream())
using (var bmp = new Bitmap(130, 30))
using (var gfx = Graphics.FromImage((System.Drawing.Image)bmp))
{
gfx.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
gfx.SmoothingMode = SmoothingMode.AntiAlias;
gfx.FillRectangle(Brushes.White, new Rectangle(0, 0, bmp.Width, bmp.Height));
//add noise
if (noisy)
{
int i, r, x, y;
var pen = new Pen(Color.Yellow);
for (i = 1; i < 10; i++)
{
pen.Color = Color.FromArgb(
(rand.Next(0, 255)),
(rand.Next(0, 255)),
(rand.Next(0, 255)));
r = rand.Next(0, (130 / 3));
x = rand.Next(0, 130);
y = rand.Next(0, 30);
gfx.DrawEllipse(pen, x - r, y - r, r, r);
}
}
//add question
gfx.DrawString(captcha, new Font("Tahoma", 15), Brushes.Gray, 2, 3);
//render as Jpeg
bmp.Save(mem, System.Drawing.Imaging.ImageFormat.Bmp);
img = this.File(mem.GetBuffer(), "image/Jpeg"); //get error for .file
}
return img;
}
}
有没有办法解决这些错误?!
答案 0 :(得分:0)
我最终解决了这段代码:
//render as Jpeg
bmp.Save(mem, ImageFormat.Jpeg);
byte[] imageBytes = mem.ToArray();
string base64String = Convert.ToBase64String(imageBytes);
//img = this.File(mem.GetBuffer(), "image/Jpeg");
return base64String;
}
//return img;