在视图中使用渲染将图像文件转换为base64

时间:2013-06-17 15:23:44

标签: c# asp.net-mvc image

我有图像验证码,除了chrome之外的所有浏览器,验证码总是重新加载相同的图片。我怎么能像素那样。我需要将我的图像转换为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.A‌​llCaches);
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCach‌​e);
filterContext.HttpContext.Response.Cache.SetNoStore();

1 个答案:

答案 0 :(得分:1)

也许另一种方法可能是在当前日期时间中包含timestamp参数以避免缓存。有时使用此技术来防止在浏览器中缓存网页,也许可以在这里使用。只是一个想法。