Skip to content

Resize images on the fly

January 6, 2011

In one of my projects I build in ASP.NET and C# I have faced the situation where I wanted to resize some images on the fly, preserving aspect ratio (proportional) .

(do not think about huge scale images but I had small ones and I wanted to resize them to not higher than: 171*105).

This was the code I used (and it works very well regarding performance too because the images are already small, some of them smaller than that size and others a little bit higher).

int intWidth = 0;
int intHeight = 0;
//path to your original photo
Bitmap bm = new System.Drawing.Bitmap(Settings.LocalPathForStaticContent + @"\ProductPictures\" + string.Format(this.randomProduct.Pictures[0].PictureName, "small"));

int intOrigWidth = bm.Width;
int intOrigHeight = bm.Height;

float intWF = ((float)171 / intOrigWidth);
float intHF = ((float)105 / intOrigHeight);

if (intWF > 1 && intHF > 1)
intWidth = intOrigWidth;
intHeight = intOrigHeight;
else if (intWF < intHF)
intWidth =(int)((float) intOrigWidth * intWF);
intHeight = (int)((float)intOrigHeight * intWF);
else if (intHF < intWF)
intWidth = (int)((float)intOrigWidth * intHF);
intHeight = (int)((float)intOrigHeight * intHF);

Now you apply intWidth and intHeight to your image control 😉


From → .NET

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: