如何在C#中将图像缩小到以字节为单位的目标大小



如何在C#中将图像缩小到以字节为单位的目标大小?具体来说,我希望拍摄一个上传到ASP.NET完整框架应用程序的图像,并将其缩小,使其小于或等于最大字节数(例如1MB(。我对缩小图像的尺寸也没问题,可以接受图像质量的一些损失。

如果您有权访问System.Drawing(.NET Full Framework(,则此代码可以工作。这种算法有点天真,因为它只是将图像的尺寸缩小10%,直到达到目标尺寸或超过最大尝试次数。它可以改进,减少暴力。

using System.Drawing;
using System.IO;
public static class ImgUtil
{
/// <summary>
/// Attempt to shrink an image down to a target size in bytes. If the input image is 
/// already small enough, it will be returned unaltered. If the image needs to be 
/// shrunk, the output image will be smaller in terms of width/height but the width/height
/// ratio will be preserved. There can be some loss of quality. The method attempts to
/// shrink the dimensions of he image incrementally until the number of bytes is equal or
/// less than the target. There is a maximum number of attempts. If the maximum number of
/// attempts is reached, the output image may be larger than the target size.
/// </summary>
/// <param name="imageBytes">>Byte array containing the image to be shrunk.</param>
/// <param name="targetSizeBytes">Target size in bytes.</param>
/// <param name="maxAttempts">Maximum number of shrink attempts, reducing the dimensions by 10% each attempt.</param>
/// <returns></returns>
public static byte[] ShrinkImage(byte[] imageBytes, int targetSizeBytes, int maxAttempts = 10)
{
using (var ms = new MemoryStream(imageBytes))
using (var img = Image.FromStream(ms))
{
var attempts = 1;
var newWidth = img.Width;
var newHeight = img.Height;
while ((imageBytes.Length > targetSizeBytes) && (attempts <= maxAttempts))
{
// Shrink by 10%
newWidth = (int)(newWidth * 0.9);
newHeight = (int)(newHeight * 0.9);
using (var bitmap = new Bitmap(img, new Size(newWidth, newHeight)))
using (var outputMs = new MemoryStream())
{
bitmap.Save(outputMs, img.RawFormat);
imageBytes = outputMs.ToArray();
}
attempts++;
}
}
return imageBytes;
}
}

相关内容

最新更新