IMG-LOGO

How to resize an image in ASP.Net Core using DotCommon.ImageUtility?

andy - 03 Apr, 2021 2488 Views 0 Comment

In the previous article, we have already provided a quick method on how to generate a thumbnail from an image in ASP.Net Core. In this article, we are going to provide a method to perform an image resize.

Here is the method on how to resize an image.

public static void ResizeImage(int size, Stream resourceImage, string filePath)
{
	try
	{
		using (Image image = Image.FromStream(resourceImage))
		{
			double newHeight = 0;
			double newWidth = 0;
			double scale = 0;
			if (image.Height > image.Width)
			{
				scale = Convert.ToSingle(size) / Convert.ToSingle(image.Height);
			}
			else
			{
				scale = Convert.ToSingle(size) / Convert.ToSingle(image.Width);
			}

			if (scale < 0 || scale > 1)
			{
				scale = 1;
			}

			newHeight = Math.Floor(Convert.ToSingle(image.Height) * scale);
			newWidth = Math.Floor(Convert.ToSingle(image.Width) * scale);

			Size NewSize = new Size(Utils.CInteger(newWidth.ToString()), Utils.CInteger(newHeight.ToString()));

			//Graphics objects can not be created from bitmaps with an Indexed Pixel Format, use RGB instead.
			PixelFormat Format = image.PixelFormat;
			if (Format.ToString().Contains("Indexed"))
			{
				Format = PixelFormat.Max;
			}

			using (Bitmap NewImage = new Bitmap(NewSize.Width, NewSize.Height))
			{
				using (Graphics Canvas = Graphics.FromImage(NewImage))
				{
					Canvas.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
					Canvas.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
					Canvas.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
					Canvas.DrawImage(image, new Rectangle(new Point(0, 0), NewSize));
					NewImage.Save(filePath, image.RawFormat);
				}
			}
		}
	}
	catch
	{

	}
}

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 ...