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 { } }