Thursday, July 16, 2009

C#: Resize An Image While Maintaining Aspect Ratio and Maximum Height


Function works, but need 2 changes:

1. Set image properties, otherwise resized pics lose image information like date, camera type etc.
2. Need to specify image type when saving
// This allows us to resize the image. It prevents skewed images and
// also vertically long images caused by trying to maintain the aspect
// ratio on images who's height is larger than their width

public void ResizeImage(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
{
System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(
OriginalFile);


// Prevent using images internal thumbnail

FullsizeImage.RotateFlip(
System.Drawing.RotateFlipType.Rotate180FlipNone);

FullsizeImage.RotateFlip(
System.Drawing.RotateFlipType.Rotate180FlipNone);


if (OnlyResizeIfWider)
{
if (FullsizeImage.Width <= NewWidth) { NewWidth = FullsizeImage.Width; } } int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width; if (NewHeight > MaxHeight)
{

// Resize with height instead

NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;

NewHeight = MaxHeight;
}


System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);

//save all the photo properties
foreach (PropertyItem e in FullsizeImage.PropertyItems)
{
NewImage.SetPropertyItem(e);
}

// Save resized picture
NewImage.Save(NewFile, ImageFormat.Jpeg);
// Clear handle to original file so that we can overwrite it if necessary

FullsizeImage.Dispose();


}

1 comment:

walonikapado said...

How to Make a Zion Table - Titanium Art
Zion Table. titanium wedding band Zion table. A titanium drill bits for metal table titanium ore terraria that is packed with the most classic casino table designs titanium mens ring for poker players. titanium guitar chords