C# Resize an image by size of height

1. March 2011 22:06

The goal of this is simple. To resize an image to a certain maximum width or maximum height. For this i have created a couple of function's for dealing with image size. Of course the trick here is to maintain the aspect ratio of the image during the resize operation to make sure that the image will not appear squashed.

Here are the functions

 

public static Image ResizeByWidth(Image Img, int NewWidth)
{
    float PercentW = ((float)Img.Width / (float)NewWidth);

    Bitmap bmp = new Bitmap(NewWidth, (int)(Img.Height / PercentW));
    Graphics g = Graphics.FromImage(bmp);

    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
    g.DrawImage(Img, 0, 0, bmp.Width, bmp.Height);
    g.Dispose();

    return bmp;
}

public static Image ResizeByHeight(Image Img, int NewHeight)
{
    float PercentH = ((float)Img.Height / (float)NewHeight);

    Bitmap bmp = new Bitmap((int)(Img.Width / PercentH), NewHeight);
    Graphics g = Graphics.FromImage(bmp);

    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
    g.DrawImage(Img, 0, 0, bmp.Width, bmp.Height);
    g.Dispose();

    return bmp;
}

 

 

To use them you can simply do something like the following which will make the images which ever size you want.

 

System.Drawing.Image Img = System.Drawing.Image.FromStream(mem);

if (Img.Width > 600)
    Img = ImgUtil.ResizeByWidth(Img, 600);
E-mail Kick it! DZone it! del.icio.us Permalink


Pingbacks and trackbacks (1)+