65.9K
CodeProject is changing. Read more.
Home

Create a thumbnail of a large size image in C#

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (8 votes)

Jul 25, 2013

CPOL
viewsIcon

57083

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.

//---------------------------------
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;
}
//-----------------------------------