Updated on

To generate an image in C# with ImageSharp, we create an Image<Rgba32> of the size we need, draw on it with DrawPolygon() from ImageSharp.Drawing inside Mutate(), and save it with SaveAsPng().

We’ll build exactly that: a blank 350 x 280 image with a red triangle on it, saved as a PNG.

To download the source code for this article, you can visit our GitHub repository.

Let’s get started.

What Is ImageSharp?

ImageSharp is a cross-platform 2D graphics library for .NET from Six Labors. It is fully managed and can be used in device, cloud, and embedded/IoT scenarios. It does not rely on the System.Drawing namespace or on Windows-specific functions, as System.Drawing.Common does.

The library is split into packages. SixLabors.ImageSharp creates, loads, processes and saves images, with operations like resizing, cropping, flipping, rotating, and adjusting the brightness and contrast. SixLabors.ImageSharp.Drawing adds vector drawing on top of it, so lines, polygons and text come from that package. SixLabors.Fonts comes along with it for text.

Not everyone gets ImageSharp for free. Open-source projects, companies under 1 million USD in annual gross revenue, and non-profits use it under the Apache License 2.0. A larger company building closed-source software needs a paid license. Newer versions also check for a license key when we build, which is one reason this article pins its versions.

We will use this library to generate an image and then draw a polygon (triangle) on it. Drawing lives in the SixLabors.ImageSharp.Drawing package. We add it together with the core package, and we pin both versions, because the newest versions no longer build this article’s code:

dotnet new console
dotnet add package SixLabors.ImageSharp --version 3.1.12
dotnet add package SixLabors.ImageSharp.Drawing --version 2.1.7

The restore prints six security warnings for ImageSharp 3.1.12. We explain them, and the pinned versions, in “Why Does This Article Pin ImageSharp 3.1.12?” further down.

How Do We Create an Image in C#?

Next, let’s create an ImageService static class in a new ImageService.cs file, where we will define some static methods, beginning with one for creating a blank image:

using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;

public static Image<Rgba32> CreateBlankImage(int width, int height)
{
    return new Image<Rgba32>(width, height);
}

Here we see our CreateBlankImage() method that creates and returns a new blank image of a specified width and height. The Image is of type Rgba32, which implies that each pixel is represented by four 8-bit values: Red, Green, Blue, and Alpha (transparency). Every pixel of a new image starts as transparent black, (0, 0, 0, 0), so our blank image is fully transparent until we draw on it.

How Do We Draw a Triangle on an Image?

Next, let’s create a static method to draw a triangle on an image:

public static void DrawTriangleOnImage(Image<Rgba32> image, PointF point1, PointF point2, PointF point3)
{
    ValidatePoint(point1);
    ValidatePoint(point2);
    ValidatePoint(point3);
    var pen = Pens.Solid(Color.Red, 3);
    image.Mutate(ctx => ctx.DrawPolygon(pen, [point1, point2, point3]));
}

public static void ValidatePoint(PointF point)
{
    if (point.X <= 0 || point.Y <= 0)
    {
        throw new ArgumentException("Point coordinates cannot be less than or equal to zero.");
    }
}

Our DrawTriangleOnImage() method takes 4 parameters: the image to draw on, along with three PointF values that define the vertices of our triangle. PointF is a struct representing an ordered pair of single-precision floating-point X and Y coordinates defining a point in a 2D plane.

First, we call our ValidatePoint() helper method to ensure all of the vertices are valid positive coordinates.

Next, we create a solid red pen with a thickness of 3 pixels. In the ImageSharp library, Pens is a static class that maintains a collection of common pen styles. The Solid() method creates a SolidPen, i.e. one without any drawing patterns.

Finally, we use the Mutate() method to perform modifications on our image. Its single argument is an Action<IImageProcessingContext>.  In our case, we pass in a lambda to call the DrawPolygon() method of the IImageProcessingContext, providing our pen and an array of vertices. DrawPolygon(), as one might guess, renders a polygon on the image context using the provided pen and coordinate array.

A polygon is a closed shape, so three points are all we pass. DrawPolygon() draws the third side from point3 back to point1 for us. ctx represents the context of the image, i.e., the work area where we make changes to our image.

How Do We Save the Image as a PNG File?

Now, let’s define a method to save an image:

public static void SaveImage(Image<Rgba32> image, string outputPath)
{
    image.SaveAsPng(outputPath);
}

Here we see our SaveImage() method, which takes two parameters: the image we wish to save and an outputPath defining where to save it.

Then, we save our image in our desired png format by calling the SaveAsPng() method, passing in our outputPath as the destination.

ImageSharp has a matching method for each format it encodes, such as SaveAsJpeg() and SaveAsWebp(), so a different file type is a one-word change.

Generating Sample Images

Now, let’s bring our previously created methods into our Program class, replacing the template code in Program.cs, to finalize our image generation:

using SixLabors.ImageSharp;

string outputPath = @"outputImage.png";

using var image = ImageService.CreateBlankImage(width: 350, height: 280);

var point1 = new PointF(50, 50);
var point2 = new PointF(250, 50);
var point3 = new PointF(150, 200);
ImageService.DrawTriangleOnImage(image, point1, point2, point3);

ImageService.SaveImage(image, outputPath);

Console.WriteLine("Image generated and saved successfully.");

First, we define our output path as a .png file in our current working directory.

Next, we create a blank image with a width of 350 pixels and a height of 280 pixels via our CreateBlankImage() method. Since Image objects are disposable, we add a using declaration (our article on managing IDisposable objects explains why that matters).

Next, we define the vertices of our triangle (point1, point2, point3), with values for their (x, y) coordinates. We then call our DrawTriangleOnImage() method with those points to render a triangle on our blank image.

Finally, we save our modified image to our specified outputPath, with a confirmation message printed on the console:

Image generated and saved successfully.

Let’s have a look at our newly saved image:

A 350 by 280 pixel PNG generated with ImageSharp, showing a red triangle outline drawn with a 3 pixel pen

Is ImageSharp Free?

Not every use of ImageSharp is free. Since ImageSharp 3 and ImageSharp.Drawing and Fonts 2, all three ship under the Six Labors Split License.

Its license file lists four cases that get the Apache License 2.0: software that is itself open source or source available, use as a transitive dependency of another package, a direct dependency at a for-profit company or individual with less than 1M USD annual gross revenue, and use by a non-profit or registered charity. Every other case needs a paid Six Labors Commercial License.

The versions we pin, ImageSharp 3.1.12 and ImageSharp.Drawing 2.1.7, carry the same license but don’t check for a key, so they build in any configuration. From ImageSharp 3.2.0 and ImageSharp.Drawing 2.2.0, the packages look for a license key at build time. Without one, a Debug build warns and a Release build stops.

Six Labors offers a free Community license, on application, to those who do not need a paid one.

Six Labors’ pricing page puts the paid case in one sentence: “A commercial license is required when a Six Labors library is used as a direct package dependency in closed-source, for-profit software produced by a business earning more than 1M USD in annual gross revenue.”

Why Does This Article Pin ImageSharp 3.1.12?

The newest ImageSharp packages change two things this article depends on, so our sample stays on ImageSharp 3.1.12 and ImageSharp.Drawing 2.1.7.

First, from ImageSharp 3.2.0 and ImageSharp.Drawing 2.2.0 on, the packages check for a Six Labors license key at build time. Without a key, a Release build stops with “No Six Labors license found.”

Second, ImageSharp.Drawing 3 removed DrawPolygon() and the other drawing extension methods on IImageProcessingContext. In the pull request that introduced the redesign, Six Labors writes: “This is a major breaking change.” On Drawing 3, our DrawTriangleOnImage() method no longer builds:

error CS1061: 'IImageProcessingContext' does not contain a definition for 'DrawPolygon' and no accessible extension method 'DrawPolygon' accepting a first argument of type 'IImageProcessingContext' could be found (are you missing a using directive or an assembly reference?)

NuGet lists six published security advisories for ImageSharp 3.1.12, four of high severity and two moderate, and the restore prints a warning for each. They are fixed only in ImageSharp 3.2.0 and in 4.1.1 or 4.1.2, the versions that check for a license key.

Conclusion

We’ve generated an image in C# with ImageSharp: a blank Image<Rgba32>, a red triangle drawn with DrawPolygon(), and a PNG file on disk. Before we ship it inside a closed-source product, the license section above tells us whether we need a paid license.

If you would rather use SkiaSharp, we also show how to generate an image with SkiaSharp in C#. For ImageMagick, there is our guide to generating images with Magick.NET.

Tested with .NET 11.0.0, SixLabors.ImageSharp 3.1.12 and SixLabors.ImageSharp.Drawing 2.1.7.