The sample code shows 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.
public void ResizeImage(string OrigFile, string NewFile, int NewWidth, int MaxHeight, bool ResizeIfWider) { System.Drawing.Image FullSizeImage = System.Drawing.Image.FromFile(OrigFile); // Ensure the generated thumbnail is not being used by rotating it 360 degrees FullSizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); FullSizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); if (ResizeIfWider) { if (FullSizeImage.Width <= NewWidth) { NewWidth = FullSizeImage.Width; } } int NewHeight = FullSizeImage.Height * NewWidth / FullSizeImage.Width; if (NewHeight > MaxHeight) // Height resize if necessary { NewWidth = FullSizeImage.Width * MaxHeight / FullSizeImage.Height; NewHeight = MaxHeight; } // Create the new image with the sizes we've calculated System.Drawing.Image NewImage = FullSizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero); FullSizeImage.Dispose(); NewImage.Save(NewFile); }
|
No responses found. Be the first to respond and make money from revenue sharing program.
|