Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Create a thumbnail of a large size image in C#

4.00/5 (8 votes)
25 Jul 2013CPOL 57K  
How to create thumbnail of a large size image in C#.

Introduction

In most projects the user uploads large size images in the application, while on many interfaces he wants to show these images in thumbnail size. This can be achieved by fixing the size of controls where the user is going to show the image but this takes more time to process due to image size being large. If it is an ASP.NET project then downloading of a large image will take too much time. In that case the user needs to save two copies of the image, one in thumbnail size and the other in actual size. The thumbnail image can be achieved by the below given method.

Using the code

The function accepts these parameters:

  1. <lcFilename> as path of large size file.
  2. <lnWidth> as width of required thumbnail.
  3. <lnHeight> as height of required thumbnail.

The function returns a Bitmap object of the changed thumbnail image which you can save on the disk.

C#
//---------------------------------
public static Bitmap CreateThumbnail(string lcFilename, int lnWidth, int lnHeight)
{
    System.Drawing.Bitmap bmpOut = null;
    try
    {
        Bitmap loBMP = new Bitmap(lcFilename);
        ImageFormat loFormat = loBMP.RawFormat;

        decimal lnRatio;
        int lnNewWidth = 0;
        int lnNewHeight = 0;

        //*** If the image is smaller than a thumbnail just return it
        if (loBMP.Width < lnWidth && loBMP.Height < lnHeight)
            return loBMP;

        if (loBMP.Width > loBMP.Height)
        {
            lnRatio = (decimal)lnWidth / loBMP.Width;
            lnNewWidth = lnWidth;
            decimal lnTemp = loBMP.Height * lnRatio;
            lnNewHeight = (int)lnTemp;
        }
        else
        {
            lnRatio = (decimal)lnHeight / loBMP.Height;
            lnNewHeight = lnHeight;
            decimal lnTemp = loBMP.Width * lnRatio;
            lnNewWidth = (int)lnTemp;
        }
        bmpOut = new Bitmap(lnNewWidth, lnNewHeight);
        Graphics g = Graphics.FromImage(bmpOut);
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
        g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);

        loBMP.Dispose();
    }
    catch
    {
        return null;
    }

    return bmpOut;
}
//----------------------------------- 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)