Geekpedia Programming Tutorials






Resize Image With Aspect Ratio

A C# method that resizes pictures and maintains their aspect ratio, optionally only if a maximum width is exceeded. The method works with both images that have a higher height than width and viceversa.

On Friday, May 2nd 2008 at 11:39 PM
By Andrei Pociu (View Profile)
*****   (Rated 5 with 2 votes)
Contextual Ads
More C# Resources
Advertisement
  1. public void ResizeImage(string OrigFile, string NewFile, int NewWidth, int MaxHeight, bool ResizeIfWider)
  2. {
  3.         System.Drawing.Image FullSizeImage = System.Drawing.Image.FromFile(OrigFile);
  4.         // Ensure the generated thumbnail is not being used by rotating it 360 degrees
  5.         FullSizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
  6.         FullSizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
  7.  
  8.         if (ResizeIfWider)
  9.         {
  10.                 if (FullSizeImage.Width <= NewWidth)
  11.                 {
  12.                         NewWidth = FullSizeImage.Width;
  13.                 }
  14.         }
  15.  
  16.         int NewHeight = FullSizeImage.Height * NewWidth / FullSizeImage.Width;
  17.         if (NewHeight > MaxHeight) // Height resize if necessary
  18.         {
  19.                 NewWidth = FullSizeImage.Width * MaxHeight / FullSizeImage.Height;
  20.                 NewHeight = MaxHeight;
  21.         }
  22.  
  23.         // Create the new image with the sizes we've calculated
  24.         System.Drawing.Image NewImage = FullSizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);
  25.         FullSizeImage.Dispose();
  26.         NewImage.Save(NewFile);
  27. }
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this code snippet
Comment Current Comments
by Mike on Thursday, May 22nd 2008 at 05:42 PM

Do it in PHP!

by Stuart on Tuesday, June 24th 2008 at 10:49 AM

Fantastic tutorial!


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Source Code
There is no related code.

Comment Related Tutorials
There are no related tutorials.

Jobs C# Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Latest Tech Bargains

Advertisement

Free Magazine Subscriptions

Today's Pictures

Today's Video

Other Resources

Latest Download

Latest Icons