Tuesday, May 3, 2011

Image resizing function using C# maintaining image ratio

You can use following function to re-size an image using C# maintaining image ratio......

public static string NewResizeImage(string MainImage, string NewLocation, int MaxWidth, int MaxHeight)
{
    try
    {
        if (MainImage.Equals(UploadLocation_DefaultImage) == true) return MainImage;
        else if (MainImage.Length > 4)
        {
            string ImageName = BCS.NewUniqueID() + MainImage.Remove(MainImage.Length - 4).Replace(WCS.UploadLocation_UploadTemp, "") + ".jpg";
            string FilePath = HttpContext.Current.Server.MapPath(NewLocation) + ImageName;

            if (File.Exists(FilePath) == false)
            {
                Size S;
                Bitmap Main = new Bitmap(HttpContext.Current.Server.MapPath(MainImage));

                if (Main.Width > MaxWidth || Main.Height > MaxHeight)
                {
                    double WidthRatio = (double)Main.Width / (double)MaxWidth;
                    double HeightRatio = (double)Main.Height / (double)MaxHeight;
                    double Ratio = Math.Max(WidthRatio, HeightRatio);
                    int NewWidth = (int)(Main.Width / Ratio);
                    int NewHeight = (int)(Main.Height / Ratio);
                    S = new Size(NewWidth, NewHeight);
                }
                else
                {
                    S = new Size(Main.Width, Main.Height);
                }
                Bitmap New = new Bitmap(Main, S);
                New.Save(FilePath, ImageFormat.Jpeg);
                New.Dispose();
                Main.Dispose();
            }
            return NewLocation + ImageName;
        }
        else return UploadLocation_DefaultImage;
    }
    catch (Exception) { return UploadLocation_DefaultImage; }
}

Abbreviation:
  • MainImage -> Image which will be re-sized
  • NewLocation  -> NewLocation
  • MaxWidth/MaxHeight -> New Sizeof re-sized image 
  • UploadLocation_DefaultImage -> Location of Default Image