ImageHelper.cs 2.1 KB

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