How to create an ASP .NET Captcha Control (part 2)

This is the second in a 3 part series on how to create an ASP .NET Captcha control. The previous post can be found here. This time we will look at how the CAPTCHA image can be generated using the built-in .NET framework classes.

Image generation approach
As described in the first post, the idea is to create an image showing a word, and let the user repeat it by typing it into a textbox. The image should be hard to read for OCR software, so that the CAPTCHA is hard to beat for automated bots. The way we will be doing this, is by stretching and warping the text, and adding noise. Luckily, this is easy to accomplish by using the GraphicsPath class to draw the string, and then use the Warp method on the GraphicsPath object.

Generating the image: Step by step
The first step in generating the image is to create a Bitmap object with the appropiate dimensions. We will also need a Font for the text, and a Brush for painting the text. I also declare a rectangle that is slightly smaller than the actual image, which will be used as the drawing bounds later. This will help to ensure, that the text fits on the image after the transformations:

        /// 
        /// Generates the CAPTCHA image.
        /// 
        /// 
        public static byte[] GenerateImage()
        {
            // Create image.
            var image = new Bitmap(size.Width, size.Height, PixelFormat.Format24bppRgb);
            var imgRectangle = new Rectangle(10, 10, image.Width - 10, image.Height - 10);
            // Get font and brush.
            var brush = new HatchBrush(HatchStyle.SolidDiamond, Color.Black, Color.FromArgb(rand.Next(160),rand.Next(160),rand.Next(160)));
            var font = new Font(fonts[rand.Next(fonts.Length - 1)], imgRectangle.Height, FontStyle.Italic, GraphicsUnit.Pixel);
 
Notice that we use a HatchBrush so that the word will be drawn using a hatch pattern. Ensuring that the text is not solid color, will help defeat OCR attacks. The actual font used is also chosen at random from a predefined list.
				
The next step is to get a Graphics object from the image, and use it to draw on the image. We'll wrap the code using the Graphics object in a using region to ensure that the instance is disposed as soon as we don't need it more. We then fill the background with white color and create a GraphicsPath instance, to which the selected Captcha word is added using the AddString method. The path object can now be warped, by stretching the corners a random amount. We also rotate the text a bit (between --10 and 10 degrees):

 
            // draw on the image.
            using(Graphics g = Graphics.FromImage(image))
            {
                g.FillRectangle(Brushes.WhiteSmoke, 0, 0, image.Width, image.Height);
                var path = new GraphicsPath();
                // Make sure text fits
                while (g.MeasureString(CaptchaWord, font).Width > imgRectangle.Width)
                    font = new Font(font.FontFamily, font.Size - 1, font.Style);
                
                path.AddString(CaptchaWord, font.FontFamily, (int)font.Style, font.Size, imgRectangle, StringFormat.GenericDefault);
                float v = 4;
                var warpPoints = new PointF[]
                                           {
                                                new PointF(rand.Next(imgRectangle.Width) / v,  rand.Next(imgRectangle.Height) / v),
                                                new PointF(imgRectangle.Width - rand.Next(imgRectangle.Width) / v,  rand.Next(imgRectangle.Height) / v),
                                                new PointF(rand.Next(imgRectangle.Width)/v, imgRectangle.Height - rand.Next(imgRectangle.Height) / v), 
                                                new PointF(imgRectangle.Width - rand.Next(imgRectangle.Width) / v, imgRectangle.Height - rand.Next(imgRectangle.Height)/ v) 
                                            };
                var warpMatrix = new Matrix();
                warpMatrix.Rotate(rand.Next(20) - 10);
                path.Warp(warpPoints, imgRectangle, warpMatrix, WarpMode.Perspective);                
                g.FillPath(brush, path);
 
The next step is to add a bit of noise to the image. This is done by drawing some small elipses (dots) randomly in the image, with a random color. This is implemented with a LINQ query selecting the details for each random dot:
 
                // Add some noise.
                var noise = from e in Enumerable.Range(0, NoiseAmount)
                         select new
                                    {
                                        X = rand.Next(image.Width),
                                        Y = rand.Next(image.Height),
                                        R = 1f + (float)rand.NextDouble() * 3f,
                                        Brush = new SolidBrush(Color.FromArgb(rand.Next(255), rand.Next(255), rand.Next(255)))
                                    };
 
                foreach (var p in noise)
                    g.FillEllipse(p.Brush, p.X, p.Y, p.R, p.R);
            }
 
Finally, the resulting image is saved to PNG format in-memory and returned from the method. 
 
   // Save to buffer and return raw png image bytes.
            using(var buffer = new MemoryStream())
            {
                image.Save(buffer, ImageFormat.Png);
                return buffer.GetBuffer();
            }
 
We will use a custom http handler by implementing IHttpHandler to send the image to the client. This will be the subject for the next post in the series. 

Comments

This post has 7 comments:
AmyWab
On 2019-02-23 00:45, AmyWab wrote:
[url=http://buspar10.com/]buspar[/url]
MaryWab
On 2019-02-24 04:39, MaryWab wrote:
[url=https://buspar10.com/]buspar[/url]
Lesheelia
On 2019-05-09 08:26, Lesheelia wrote:
Propecia Online Pharmacy Xenical Zithromax Azithromycin Dosage Le Viagra Est Il En Vente Libre En Pharmacie [url=http://cheapvia25mg.com]viagra online[/url] Cialis Prix France Sale Secure Ordering Macrobid 100mg Las Vegas
PLESTYPEKS
On 2019-09-03 14:33, PLESTYPEKS wrote:
The cleansing firm carries out cleaning of spaces of various dimensions and configurations. The company's professionals supply cleaning with the help of contemporary technologies, have unique devices, and also have actually certified cleaning agents in their toolbox. Along with the above benefits, red wines supply: beneficial rates; cleansing quickly; high quality results; more than 100 positive reviews. Cleansing workplaces will certainly help keep your work environment in order for the most productive work. Any type of business is extremely crucial environment in the team. Cleaning up solutions that can be purchased cheaply currently can aid to organize it and also provide a comfortable room for labor. If necessary, we leave cleaning up the kitchen 2-3 hrs after placing the order. You obtain cleansing immediately. We supply expert [url=https://maidservicenyc.pro/]room maid service[/url] for personal clients. Utilizing European equipment and licensed devices, we achieve optimal outcomes as well as provide cleansing in a short time. We offer discount rates for those who utilize the solution for the very first time, along with positive regards to cooperation for normal clients. Our friendly group uses you to obtain accustomed with positive regards to cooperation for business clients. We responsibly approach our tasks, tidy making use of specialist cleansing products and also specific tools. Our workers are trained, have medical books and also are familiar with the nuances of removing facility as well as hard-to-remove dust from surfaces. We offer high-grade cleaning for huge ventures and small companies of different instructions, with a price cut of as much as 25%.
Normanhal
On 2019-09-24 09:25, Normanhal wrote:
Specialist cleansing today is greater than only cleaning: present day devices, devices as well as approaches of work transform it right into a genuine state-of-the-art process that drastically modifies the conventional understanding of what it suggests to definitely "tidy". In property cleaning services - best [url=https://maidsmanhattan.club/service-maid/]service maids[/url] - it is actually very easy, hassle-free as well as budget friendly along with our business. Depend on the cleanliness leaders to house cleansing Brooklyn! Our company use expert soaps as well as technical devices of worldwide suppliers in our job and also do a great project with cleansing of any kind of complexity. [url=https://maidsmanhattan.club/][size=8]Local home cleaners new-york[/size][/url] Participation with the company is actually the backer of a remarkable, lucrative and also effective cleaning of specialist house cleaning and also surrounding regions. Presently, residence cleaning services from our business are used in New Jacket. Cherish and also you the genuine benefits and functional benefits of our organisation proposition. Through authorizing an irreversible service deal with our team, you will definitely have the ability to leave the need to keep a big workers of technical personnel, which, in turn, are going to improve costs. The expense of the facility, daily, standard home cleaning of Staten Island, done through our employees, will consistently be actually less than the cost of salaries for cleaning services, the purchase of cleansing products and also tools. [size=6]Detailed house cleaning manhattan[/size] Leave behind an ask for on the internet site, define your title or firm name, contact contact number and day of desired cleansing, leave your dreams and also criteria in an information to the supervisor if essential, at that point our expert will definitely call you in the least opportunity as well as specify the time, time as well as work place!
Kelcomi
On 2019-10-01 17:59, Kelcomi wrote:
Pregnancy Category And Cephalexin Viagra Bestellen Deutschland [url=http://rxbill7.com]cialis for sale[/url] Priligy Cost
KRsheni
On 2019-10-12 21:31, KRsheni wrote:
We create original interiors , paying close attention to conditions reliability and functionality . Work is underway with customer on all, without exception stages produce multilateral analysis location rooms ,produce preliminary calculations. your any questions . Kitchen remodel colonial home considered one of especially labor-intensive cases In the firm Limited liability Partnership NDYKF Queens Village involved trained specialists, exactly they all know about Kitchen remodel for less than $5000. The Enterprise ready to provide first class Professional kitchen remodel by affordable tariffs . Specialists with great experience work help fully change in a matter of days . The price depends on selected style of kitchen. Any room apartments, houses, cottages or other housing Bruckner unique and carries personal functional load. This mostly is related to modern kitchens. Easy kitchen renovations Carroll Gardens : [url=https://kitchen-renovation.club]kitchen renovation manhattan[/url]

Leave a comment:

Your name:
Your email:
Comment:
Verification: What is the result of 4 minus 4 ?
Answer incorrect. Please try again.