Bitmap manipulation extension methods for C#

Helper methods for bitmap manipulation in .NET

  • Share

This is a class I used few years back for some image manipulation in C#.

Over the years, I was adding more methods and code snippets I needed and some stuff I found on Internet, so it grow to a useful collection of Bitmap manipulation methods. Recently, all static methods are converted to extension methods for easier usage in code.

Feel free to use it in your projects and suggest any method for image manipulation which might be useful so it can be included in this class.

Here is a simple sample code which resizes original image to 300x300 pixels and adds watermark and diagonal line:

new Bitmap("C:\\Temp\\lake.jpg").ResizeToSquare(300).DrawDiagonalLines("gray",System.Drawing.Drawing2D.DashStyle.Solid).DrawTextWatermark("dejanstojanovic.net", "Arial");
    

Out

Because all output types of extension methods are bitmap, you can just easily concatenate what ever you want to do with your bitmap. For example, just adding MakeGrayscale() to the previous code we will get the same image but in grayscale.

new Bitmap("C:\\Temp\\lake.jpg").ResizeToSquare(300).DrawDiagonalLines("gray",System.Drawing.Drawing2D.DashStyle.Solid).DrawTextWatermark("dejanstojanovic.net", "Arial").MakeGrayscale();
    

Out (1)

And by adding just RoundedCornerImage(50) you easily get rounded image.

new Bitmap("C:\\Temp\\lake.jpg").ResizeToSquare(300).DrawDiagonalLines("gray",System.Drawing.Drawing2D.DashStyle.Solid).DrawTextWatermark("dejanstojanovic.net", "Arial").MakeGrayscale().RoundedCornerImage(50);
    

Out (2)

Note

If you are planning to generate images on the fly in ASP.NET application, consider saving images to file system after they are generated to avoid high usage of processor and memory for every request. Http handlers without some sort of caching (saving previously generated file) are not a good practice

  • Share

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.

Comments for this article

comments powered by Disqus