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. }
Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to Geekpedia.com. With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology.
Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach