Sunday, June 10, 2018

Using System.Drawing to create an image thumbnail cropped at 1:1

Creating a thumbnail for an image is very easy if you are developing for .Net Framework or .Net Core, since both platforms offer the System.Drawing packages. The tricky solution is cropping the image in perfect square format without distorting or stretching the image.

The following code shows how to exactly do a center crop while generating a thumbnail, the original image needs to be scaled down to match size of the thumbnail while maintaining the aspect ratio first, then moved to an offset calculated previously such that the final drawing removes the pixels that were supposed to be cut off during the cropping. The offset represents the number of pixels of that side that require to be cropped off.

It should be kept in mind that on .Net Core the package must cover all platforms. For that case there are three nuget packages available for .Net Core for Windows, Linux, and OSX each.


No comments :

Post a Comment

enter comment