DrawingUtils.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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(ImageDimensions size,
  19. int width,
  20. int height,
  21. int maxWidth,
  22. int maxHeight)
  23. {
  24. int newWidth = size.Width;
  25. int newHeight = size.Height;
  26. if (width > 0 && height > 0)
  27. {
  28. newWidth = width;
  29. newHeight = height;
  30. }
  31. else if (height > 0)
  32. {
  33. newWidth = GetNewWidth(newHeight, newWidth, height);
  34. newHeight = height;
  35. }
  36. else if (width > 0)
  37. {
  38. newHeight = GetNewHeight(newHeight, newWidth, width);
  39. newWidth = width;
  40. }
  41. if (maxHeight > 0 && maxHeight < newHeight)
  42. {
  43. newWidth = GetNewWidth(newHeight, newWidth, maxHeight);
  44. newHeight = maxHeight;
  45. }
  46. if (maxWidth > 0 && maxWidth < newWidth)
  47. {
  48. newHeight = GetNewHeight(newHeight, newWidth, maxWidth);
  49. newWidth = maxWidth;
  50. }
  51. return new ImageDimensions(newWidth, newHeight);
  52. }
  53. /// <summary>
  54. /// Gets the new width.
  55. /// </summary>
  56. /// <param name="currentHeight">Height of the current.</param>
  57. /// <param name="currentWidth">Width of the current.</param>
  58. /// <param name="newHeight">The new height.</param>
  59. /// <returns>the new width</returns>
  60. private static int GetNewWidth(int currentHeight, int currentWidth, int newHeight)
  61. => Convert.ToInt32((double)newHeight / currentHeight * currentWidth);
  62. /// <summary>
  63. /// Gets the new height.
  64. /// </summary>
  65. /// <param name="currentHeight">Height of the current.</param>
  66. /// <param name="currentWidth">Width of the current.</param>
  67. /// <param name="newWidth">The new width.</param>
  68. /// <returns>System.Double.</returns>
  69. private static int GetNewHeight(int currentHeight, int currentWidth, int newWidth)
  70. => Convert.ToInt32((double)newWidth / currentWidth * currentHeight);
  71. }
  72. }