将图像文件转换为base64,并在视图中渲染
本文关键字:视图 文件 图像 转换 base64 | 更新日期: 2023-09-27 18:18:56
我有图像验证码,在除chrome以外的所有浏览器中,验证码总是重新加载相同的图片。我怎么能做到呢?Mb我需要将我的图像转换为base64string,我尝试将nocache属性设置为我的控制器/动作,但它不起作用。
public ActionResult CaptchaImageComm(string prefix, bool noisy = false)
{
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["Captcha5"] = a + b;
//image stream
FileContentResult img = null;
string result = null;
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.Jpeg);
img = this.File(mem.GetBuffer(), "image/Jpeg");
}
return img;
}
和我的动作:
<img alt="Captcha" src="@Url.Action("CaptchaImageComm", "DataCaptcha")" style="" />
我设置缓存设置如下:
filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
filterContext.HttpContext.Response.Cache.SetNoStore();
另一种方法可能是在当前日期时间中包含时间戳参数,以避免缓存。此技术有时用于防止在浏览器中缓存网页,也许可以在这里使用。这只是一个想法。