C# code: Create image's thumbnail

Published 7/9/2007 by Admin in Codes
Tags:


After took several hours looking for good C# code to create a thumbnail from an image, I decided to convert the good VB code into C#, and tweak a bit to have the function save the thumbnail into it's original image file format.

public bool MakeThumbnail(string thumb, string img, int width, int height, bool keepOriginalRatio)
    {
        System.Drawing.Image fullSizeImg;
        try
        {
            fullSizeImg = new System.Drawing.Bitmap(img);
        }
        catch (Exception ex)
        {
            return false;
        }

        if ((fullSizeImg.Width <= width) && (fullSizeImg.Height <= height))
        {
            //Smaller or same size as thumbnail so no need to do anything special
            try
            {
                fullSizeImg.Save(thumb);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        else
        {
            if (keepOriginalRatio)
            {
                if (width <= 0)
                {
                    width = height * fullSizeImg.Width / fullSizeImg.Height;
                }
                else if (height <= 0)
                {
                    height = width * fullSizeImg.Height / fullSizeImg.Width;
                }
                else
                {
                    float TargetRatio = width / height;
                    float CurrentRatio = fullSizeImg.Width / fullSizeImg.Height;
                   
                    if (CurrentRatio > TargetRatio) //We'll scale height
                    { height = width / Convert.ToInt16(CurrentRatio); }
                    else // We'll scale width
                    { width = height * Convert.ToInt16(CurrentRatio); }
                }
            }

            System.Drawing.Image thumbNailImg = new System.Drawing.Bitmap(fullSizeImg, width, height);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(thumbNailImg);

            g.FillRectangle(System.Drawing.Brushes.White, 0, 0, width, height);
            g.DrawImage(fullSizeImg, 0, 0, width, height);

            try
            {
                thumbNailImg.Save(thumb, fullSizeImg.RawFormat);
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        return false;
    }

Sample code to use:

//Upload file
string savePath = _configReader.GetValue("FolderPathToSaveFile", "".GetType()).ToString();
string filename = null;

if (FileUpload.HasFile)
{
   filename = FileUpload.FileName;
   FileUpload.SaveAs(savePath + filename);
   MakeThumbnail(savePath + "thumb_" + filename, savePath + filename, 100, 0, true);
}

Currently rated 3.0 by 1 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

ShockingLabs.com

Malaysian Software Developer