PROWAREtech

articles » current » dot-net » sixlabors-imagesharp-crop-image-to-square

.NET: Crop Image to Square using SixLabors.ImageSharp v3.x

Use SixLabors.ImageSharp to crop an image to a square, written in C#.

It may be necessary to crop an image to a square, such as preparing the image for a convolutional neural network.

See accessing the pixels and color information.


using SixLabors.ImageSharp;
using (var bmp = Image.Load("file.jpg"))
{
	if(bmp.Width != bmp.Height)
	{
		int size = Math.Min(bmp.Width, bmp.Height);

		var cropRectangle = new Rectangle((bmp.Width - size) / 2, (bmp.Height - size) / 2, size, size);

		bmp.Mutate(x => x.Crop(cropRectangle));
	}
	int width = 256;
	int height = 256;
	bmp.Mutate(x => x.Resize(width, height)); // this is optional!!
}

PROWAREtech

Hello there! How can I help you today?
Ask any question

PROWAREtech

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
ACCEPT REJECT