MVC中产生高质量的验证码

 
    public void Render(string challengeGuid)
    {
        // Retrieve the solution text from Session[]
        string key = CaptchaHelper.SessionKeyPrefix + challengeGuid;
        string solution = (string)HttpContext.Session[key];
 
        if (solution != null) {
            // Make a blank canvas to render the CAPTCHA on
            using (Bitmap bmp = new Bitmap(ImageWidth, ImageHeight))
            using (Graphics g = Graphics.FromImage(bmp)) 
            using (Font font = new Font(FontFamily, 1f)) {
                g.Clear(Background);
 
                // Perform trial rendering to determine best font size
                SizeF finalSize;
                SizeF testSize = g.MeasureString(solution, font);
                float bestFontSize = Math.Min(ImageWidth / testSize.Width,
                                        ImageHeight / testSize.Height) * 0.95f;
 
                using (Font finalFont = new Font(FontFamily, bestFontSize)) {
                    finalSize = g.MeasureString(solution, finalFont);
                }
 
                // Get a path representing the text centered on the canvas
                g.PageUnit = GraphicsUnit.Point;
                PointF textTopLeft = new PointF((ImageWidth - finalSize.Width) / 2,
                                              (ImageHeight - finalSize.Height) / 2);
                using(GraphicsPath path = new GraphicsPath()) {
                    path.AddString(solution, new FontFamily(FontFamily), 0,
                        bestFontSize, textTopLeft, StringFormat.GenericDefault);
 
                    // Render the path to the bitmap
                    g.SmoothingMode = SmoothingMode.HighQuality;
                    g.FillPath(Foreground, path);
                    g.Flush();
 
                    // Send the image to the response stream in PNG format
                    Response.ContentType = "image/png";
                    using (var memoryStream = new MemoryStream()) {
                        bmp.Save(memoryStream, ImageFormat.Png);
                        memoryStream.WriteTo(Response.OutputStream);
                    }
                }
            }
        }
    }
}

你可能感兴趣的:(MVC中产生高质量的验证码)