ImageHelper.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Drawing.Imaging;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace Optimizer
  9. {
  10. public static class ImageHelper
  11. {
  12. private static float[][] _colorMatrixElements =
  13. {
  14. new float[] {(float)0.299, (float)0.299, (float)0.299, 0, 0},
  15. new float[] {(float)0.587, (float)0.587, (float)0.587, 0, 0},
  16. new float[] {(float)0.114, (float)0.114, (float)0.114, 0, 0},
  17. new float[] {0, 0, 0, 1, 0},
  18. new float[] {0, 0, 0, 0, 1}
  19. };
  20. private static ColorMatrix _grayscaleColorMatrix = new ColorMatrix(_colorMatrixElements);
  21. public static ImageAttributes GetGrayscaleAttributes()
  22. {
  23. ImageAttributes attr = new ImageAttributes();
  24. attr.SetColorMatrix(_grayscaleColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
  25. return attr;
  26. }
  27. public static Size RescaleImageToFit(Size imageSize, Size canvasSize)
  28. {
  29. // Code "borrowed" from http://stackoverflow.com/questions/1940581/c-sharp-image-resizing-to-different-size-while-preserving-aspect-ratio
  30. // and the Math.Min improvement from http://stackoverflow.com/questions/6501797/resize-image-proportionally-with-maxheight-and-maxwidth-constraints
  31. // Figure out the ratio
  32. double ratioX = (double)canvasSize.Width / (double)imageSize.Width;
  33. double ratioY = (double)canvasSize.Height / (double)imageSize.Height;
  34. // use whichever multiplier is smaller
  35. double ratio = Math.Min(ratioX, ratioY);
  36. // now we can get the new height and width
  37. int newHeight = Convert.ToInt32(imageSize.Height * ratio);
  38. int newWidth = Convert.ToInt32(imageSize.Width * ratio);
  39. Size resizedSize = new Size(newWidth, newHeight);
  40. if (resizedSize.Width > canvasSize.Width || resizedSize.Height > canvasSize.Height)
  41. {
  42. throw new Exception("ImageHelper.RescaleImageToFit - Resize failed!");
  43. }
  44. return resizedSize;
  45. }
  46. }
  47. }