调整图像大小以保持纵横比

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了调整图像大小以保持纵横比相关的知识,希望对你有一定的参考价值。

  1. /// <summary>
  2. /// Allows for image resizing. if AllowLargerImageCreation = true
  3. /// you want to increase the size of the image
  4. /// </summary>
  5. /// <param name="bytes"></param>
  6. /// <param name="NewWidth"></param>
  7. /// <param name="MaxHeight"></param>
  8. /// <param name="AllowLargerImageCreation"></param>
  9. /// <returns></returns>
  10. /// <remarks></remarks>
  11. public static byte[] ResizeImage(byte[] bytes, int NewWidth, int MaxHeight, bool AllowLargerImageCreation)
  12. {
  13.  
  14. Image FullsizeImage = null;
  15. Image ResizedImage = null;
  16. //Cast bytes to an image
  17. FullsizeImage = byteArrayToImage(bytes);
  18.  
  19. // Prevent using images internal thumbnail
  20. FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
  21. FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
  22.  
  23. // If we are re sizing upwards to a bigger size
  24. if (AllowLargerImageCreation) {
  25. if (FullsizeImage.Width <= NewWidth) {
  26. NewWidth = FullsizeImage.Width;
  27. }
  28. }
  29.  
  30. //Keep aspect ratio
  31. int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
  32. if (NewHeight > MaxHeight) {
  33. // Resize with height instead
  34. NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
  35. NewHeight = MaxHeight;
  36. }
  37.  
  38. ResizedImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);
  39.  
  40. // Clear handle to original file so that we can overwrite it if necessary
  41. FullsizeImage.Dispose();
  42.  
  43. return imageToByteArray(ResizedImage);
  44. }
  45.  
  46.  
  47. /// <summary>
  48. /// convert image to byte array
  49. /// </summary>
  50. /// <param name="imageIn"></param>
  51. /// <returns></returns>
  52. private static byte[] imageToByteArray(System.Drawing.Image imageIn)
  53. {
  54. MemoryStream ms = new MemoryStream();
  55. imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
  56. return ms.ToArray();
  57. }
  58.  
  59.  
  60. /// <summary>
  61. /// Convert a byte array to an image
  62. /// </summary>
  63. /// <remarks></remarks>
  64. public static Image byteArrayToImage(byte[] byteArrayIn)
  65. {
  66. MemoryStream ms = new MemoryStream(byteArrayIn);
  67. Image returnImage = Image.FromStream(ms);
  68. return returnImage;
  69. }

以上是关于调整图像大小以保持纵横比的主要内容,如果未能解决你的问题,请参考以下文章

使用“Vstack”将图像大小调整为屏幕宽度,同时保持纵横比

在 CSS FlexBox 布局中自动调整图像大小并保持纵横比?

枕头调整图像大小 - 保持纵横比

在 iOS 中调整图像大小并保持其纵横比

调整图像大小保持纵横比

如何按比例调整图像大小/保持纵横比?