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.
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. }