ImageHelper.cs 2.3 KB

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