IMG-LOGO

How to generate a thumbnail from an image in ASP.Net Core using DotCommon.ImageUtility?

andy - 03 Apr, 2021 5723 Views 0 Comment

If you need to generate a thumbnail image from a stream source. You can use a library called DotCommon.ImageUtility.

In your .Net Core project, go to Tools > Nuget Package Manager > Package Manager Console.

Go to the following site to get the latest command for installing the library.

https://www.nuget.org/packages/DotCommon.ImageUtility/

This is an example command to install the package.

Install-Package DotCommon.ImageUtility -Version 4.2.4

Here is the method on how to generate thumbnail .Net Core.

public static void GenerateThumbnail(int dimension, Stream resourceImage, string savePath)
{
	try
	{
		using (Image image = Image.FromStream(resourceImage))
		{
			float percentageResize = 0;
			float percentageResizeW = 0;
			float percentageResizeH = 0;
			int sourceX = 0;
			int sourceY = 0;
			int destX = 0;
			int destY = 0;
			int sourceWidth = image.Width;
			int sourceHeight = image.Height;

			percentageResizeW = ((float)dimension / (float)sourceWidth);
			percentageResizeH = ((float)dimension / (float)sourceHeight);
			if (percentageResizeH < percentageResizeW)
			{
				percentageResize = percentageResizeW;
				destY = System.Convert.ToInt16((dimension - (sourceHeight * percentageResize)) / 2);
			}
			else
			{
				percentageResize = percentageResizeH;
				destX = System.Convert.ToInt16((dimension - (sourceWidth * percentageResize)) / 2);
			}

			int destWidth = (int)Math.Round(sourceWidth * percentageResize);
			int destHeight = (int)Math.Round(sourceHeight * percentageResize);

			using (Bitmap objBitmap = new Bitmap(dimension, dimension))
			{
				objBitmap.SetResolution(image.HorizontalResolution, image.VerticalResolution);
				using (Graphics objGraphics = Graphics.FromImage(objBitmap))
				{
					objGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
					objGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
					objGraphics.DrawImage(image, new Rectangle(destX, destY, destWidth, destHeight), new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), GraphicsUnit.Pixel);
					objBitmap.Save(savePath, ImageFormat.Png);
				}
			}
		}
	}
	catch (Exception ex)
	{
		//do something for error handler exception
	}
}

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles

ASP.Net Core 2.0 - HTTP Error 502.5

When you deploy your asp net Core 2 0 application you may receive the following error message which is about processing failure or HTTP error 502 5 This particular error is maybe caused by the program can t start because ...