调整图像大小以保持纵横比
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了调整图像大小以保持纵横比相关的知识,希望对你有一定的参考价值。
/// <summary> /// Allows for image resizing. if AllowLargerImageCreation = true /// you want to increase the size of the image /// </summary> /// <param name="bytes"></param> /// <param name="NewWidth"></param> /// <param name="MaxHeight"></param> /// <param name="AllowLargerImageCreation"></param> /// <returns></returns> /// <remarks></remarks> public static byte[] ResizeImage(byte[] bytes, int NewWidth, int MaxHeight, bool AllowLargerImageCreation) { Image FullsizeImage = null; Image ResizedImage = null; //Cast bytes to an image FullsizeImage = byteArrayToImage(bytes); // Prevent using images internal thumbnail FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); // If we are re sizing upwards to a bigger size if (AllowLargerImageCreation) { if (FullsizeImage.Width <= NewWidth) { NewWidth = FullsizeImage.Width; } } //Keep aspect ratio int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width; if (NewHeight > MaxHeight) { // Resize with height instead NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height; NewHeight = MaxHeight; } ResizedImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero); // Clear handle to original file so that we can overwrite it if necessary FullsizeImage.Dispose(); return imageToByteArray(ResizedImage); } /// <summary> /// convert image to byte array /// </summary> /// <param name="imageIn"></param> /// <returns></returns> private static byte[] imageToByteArray(System.Drawing.Image imageIn) { imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); return ms.ToArray(); } /// <summary> /// Convert a byte array to an image /// </summary> /// <remarks></remarks> public static Image byteArrayToImage(byte[] byteArrayIn) { Image returnImage = Image.FromStream(ms); return returnImage; }
以上是关于调整图像大小以保持纵横比的主要内容,如果未能解决你的问题,请参考以下文章
使用“Vstack”将图像大小调整为屏幕宽度,同时保持纵横比