Method for resizing pictures with aspect ratio

The GenerateThumbnail() C# function resizes pictures for various formats, such as JPEG, PNG and BMP, and maintains their aspect ratio.

Contextual Ads

More C# Resources


using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
public void GenerateThumbnail(string filePath, string origFileName, string thumbFileName, ImageFormat imgFormat)
    System.Drawing.Image origImage = System.Drawing.Image.FromFile(filePath + @"\" + origFileName);
    float WidthPer, HeightPer;
    int NewWidth, NewHeight;
    if (origImage.Width > origImage.Height)
        NewWidth = ThumbnailSize.Width;
        WidthPer = (float)ThumbnailSize.Width / origImage.Width;
        NewHeight = Convert.ToInt32(origImage.Height * WidthPer);
        NewHeight = ThumbnailSize.Height;
        HeightPer = (float)ThumbnailSize.Height / origImage.Height;
        NewWidth = Convert.ToInt32(origImage.Width * HeightPer);
    System.Drawing.Image origThumbnail = new Bitmap(NewWidth, NewHeight, origImage.PixelFormat);
    Graphics oGraphic = Graphics.FromImage(origThumbnail);
    oGraphic.CompositingQuality = CompositingQuality.HighQuality;
    oGraphic.SmoothingMode = SmoothingMode.HighQuality;
    oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
    Rectangle oRectangle = new Rectangle(0, 0, NewWidth, NewHeight);
    oGraphic.DrawImage(origImage, oRectangle);
    origThumbnail.Save(filePath + @"\" + thumbFileName, imgFormat);
Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology. Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top