DrawingUtils.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System;
  2. namespace MediaBrowser.Model.Drawing
  3. {
  4. /// <summary>
  5. /// Class DrawingUtils.
  6. /// </summary>
  7. public static class DrawingUtils
  8. {
  9. /// <summary>
  10. /// Resizes a set of dimensions.
  11. /// </summary>
  12. /// <param name="size">The original size object.</param>
  13. /// <param name="width">A new fixed width, if desired.</param>
  14. /// <param name="height">A new fixed height, if desired.</param>
  15. /// <param name="maxWidth">A max fixed width, if desired.</param>
  16. /// <param name="maxHeight">A max fixed height, if desired.</param>
  17. /// <returns>A new size object.</returns>
  18. public static ImageDimensions Resize(
  19. ImageDimensions size,
  20. int width,
  21. int height,
  22. int maxWidth,
  23. int maxHeight)
  24. {
  25. int newWidth = size.Width;
  26. int newHeight = size.Height;
  27. if (width > 0 && height > 0)
  28. {
  29. newWidth = width;
  30. newHeight = height;
  31. }
  32. else if (height > 0)
  33. {
  34. newWidth = GetNewWidth(newHeight, newWidth, height);
  35. newHeight = height;
  36. }
  37. else if (width > 0)
  38. {
  39. newHeight = GetNewHeight(newHeight, newWidth, width);
  40. newWidth = width;
  41. }
  42. if (maxHeight > 0 && maxHeight < newHeight)
  43. {
  44. newWidth = GetNewWidth(newHeight, newWidth, maxHeight);
  45. newHeight = maxHeight;
  46. }
  47. if (maxWidth > 0 && maxWidth < newWidth)
  48. {
  49. newHeight = GetNewHeight(newHeight, newWidth, maxWidth);
  50. newWidth = maxWidth;
  51. }
  52. return new ImageDimensions(newWidth, newHeight);
  53. }
  54. /// <summary>
  55. /// Gets the new width.
  56. /// </summary>
  57. /// <param name="currentHeight">Height of the current.</param>
  58. /// <param name="currentWidth">Width of the current.</param>
  59. /// <param name="newHeight">The new height.</param>
  60. /// <returns>The new width.</returns>
  61. private static int GetNewWidth(int currentHeight, int currentWidth, int newHeight)
  62. => Convert.ToInt32((double)newHeight / currentHeight * currentWidth);
  63. /// <summary>
  64. /// Gets the new height.
  65. /// </summary>
  66. /// <param name="currentHeight">Height of the current.</param>
  67. /// <param name="currentWidth">Width of the current.</param>
  68. /// <param name="newWidth">The new width.</param>
  69. /// <returns>System.Double.</returns>
  70. private static int GetNewHeight(int currentHeight, int currentWidth, int newWidth)
  71. => Convert.ToInt32((double)newWidth / currentWidth * currentHeight);
  72. }
  73. }