This site uses cookies to deliver our services. By using this site, you acknowledge that you have read and understand our Cookie and Privacy policy. Your use of Kontext website is subject to this policy. Allow Cookies and Dismiss

Graphics Programming and Image Processing in .NET Core 2.x

454 views 0 comments last modified about 9 months ago Raymond Tang core 2 .net core

In .NET Core 2.x, Windows Forms or WPF are not implemented since they are based on GDI+ and DirectX respectively in Windows. In .NET Core 3.0, there is plan to add Desktop Packs which includes UWP. WPF and Windows Forms. However, they will still be Windows-only. In .NET Core applications, you may need to generate or process images. To do that, there are quite a few third party libraries you can use even they don’t implement all the functionalities in .NET Framework. For example, the following open source projects are available to use:

  • CoreCompat.System.Drawing
  • ImageSharp
  • Magick.NET
  • SkiaSharp
  • FreeImage-dotnet-core
  • MagicScaler

In Microsoft official .NET blog, there is a post summarizes these core features of these libraries and performance comparisons.

In this page, I am going to show you how to draw a captcha image using CoreCompat.System.Drawing.

Sample code

The following code snippet shows how to create a bitmap image and save to HTTP response stream.

The main steps used are listed below:

  • Instantiate a Bitmap object
  • Use the Bitmap object to create a Graphics object
  • Use the Graphics object to draw strings and lines. Font style and colour brushes can be applied. For these .NET core libraries, not all the .NET Framework brushes or fonts are implemented.
  • Save the Bitmap object as file or into streams.

The code is very similar to the one I created in one of the previous posts.

private void ProcessRequest(HttpContext context)
             // Setup output format
             context.Response.ContentType = "image/gif";
             Random random = new Random();

            // Generate random characters
             StringBuilder s = new StringBuilder();

            // Create the image
             using (Bitmap bitmap = new Bitmap(captchaOptions.ImageWidth, captchaOptions.ImageHeight))
                 // Create the graphics
                 using (Graphics graphics = Graphics.FromImage(bitmap))
                     // Write bg color
                     graphics.FillRectangle(new SolidBrush(bgColor), 0, 0, captchaOptions.ImageWidth, captchaOptions.ImageHeight);

                    // Font
                     using (Font font = new Font(FontFamily.GenericSerif, 32, FontStyle.Bold | FontStyle.Italic, GraphicsUnit.Pixel))
                         for (int i = 0; i < captchaOptions.CodeLength; i++)
                             s.Append(captchaOptions.CaptchaString.Substring(random.Next(0, captchaOptions.CaptchaString.Length - 1), 1));
                             // Write char to the graphic
                             graphics.DrawString(s[s.Length - 1].ToString(), font, new SolidBrush(codeColor), i * 32, random.Next(0, 24));

                    // Add obstructions
                     using (Pen pen = new Pen(new SolidBrush(this.obsColor), 1))
                         for (int i = 0; i < 10; i++)
                             graphics.DrawLine(pen, new Point(random.Next(0, captchaOptions.ImageWidth - 1), random.Next(0, captchaOptions.ImageHeight - 1)), new Point(random.Next(0, captchaOptions.ImageWidth - 1), random.Next(0, captchaOptions.ImageHeight - 1)));
                     for (int i = 0; i < 100; i++)
                         bitmap.SetPixel(random.Next(captchaOptions.ImageWidth), random.Next(captchaOptions.ImageHeight), Color.FromArgb(random.Next()));

                    context.Session.Set(captchaOptions.SessionName, Encoding.UTF8.GetBytes(s.ToString().ToLower()));

                    // Save image
                     bitmap.Save(context.Response.Body, System.Drawing.Imaging.ImageFormat.Gif);

Sample output

The following is a sample captcha image in this website.


Related pages

Set AttachDbFilename as Relative Path in .NET Core

749 views   0 comments last modified about 8 months ago

.NET Framework, you can use |DataDirectory| to configure connection string when connecting to SQL Server database file via attach mode: AttachDbFilename=|DataDirectory|\dbname.mdf In .NET Core, you cannot directly set SQL Server Express connec...

View detail

Instantiate a Service in ConfigureServices Method in .NET Core

74 views   0 comments last modified about 8 months ago

.NET Core is built in with dependency injection. Usually method ConfigureServices in Startup class is used to register services in the container. The signature of the method looks like the following: public void ConfigureServices(IServiceC...

View detail

ASP.NET Core 2.1 Error - 'Cyrillic' is not a supported encoding name

578 views   0 comments last modified about 8 months ago

After upgrading to ASP.NET Core 2.1 (.NET Core SDK 2.1.301), you may encounter the following error about encoding: System.ArgumentException &nbsp;&nbsp; HResult=0x80070057 &nbsp;&nbsp; Message='Cyrillic' is not a supported encoding name. For information on defining a custo...

View detail

SQLite in .NET Core with Entity Framework Core

995 views   0 comments last modified about 8 months ago

SQLite is a self-contained and embedded SQL database engine. In .NET Core, Entity Framework Core provides APIs to work with SQLite. This page provides sample code to create a SQLite database using package Microsoft.EntityFrameworkCore.Sqlite . Create sample project ...

View detail

ASP.NET Core 2 with Bootstrap 4 Bundler Minifier Issue: Expected semicolon or closing curly-brace found '-'

1261 views   1 comments last modified about 2 years ago

Background When upgrading Bootstrap to v4.0.0 release, the bundler and minifier doesn’t work properly due to CSS variable is commonly used: :root{--blue:#007bff; About 26 errors will show up in the Error List with the following message: ...

View detail

Tuples in C# (4.x, 7.0, 7.1)

252 views   0 comments last modified about 12 months ago

What is a tuple? Tuple is an ordered sequence, fixed-size, immutable and of heterogeneous objects. Tuple has been existing in other languages such as F#, Python, Perl and etc. for a long time. It was first introduced into C# from C# 4.0 and has been evolving over time. Since C# 7.1, tuple...

View detail

Add comment

Please login first to add comments.  Log in New user?  Register

Comments (0)

No comments yet.


  • enquiry[at]