我正在使用 ImageProcessor 来降低图像的分辨率或质量,但我不知道如何确保图像生成的大小低于 5 兆字节。我尝试将图像尺寸设置为 3840-2160,但我想使用更好的选项。
这是我的代码:
private static byte[] redimensionImage(ref byte[] photoBytes)
{
var byteCuantity = ConvertBytesToMegabytes(photoBytes.Count());
ISupportedImageFormat format = new JpegFormat();
using (MemoryStream inStream = new MemoryStream(photoBytes))
{
using (MemoryStream outStream = new MemoryStream())
{
// Initialize the ImageFactory using the overload to preserve EXIF metadata.
using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
{
// Load, resize, set the format and quality and save an image.
using (var imageProcessor = imageFactory.Load(inStream))
{
var originalHeight = imageProcessor.Image.Size.Height;
var originalWidth = imageProcessor.Image.Size.Width;
//calculate aspect ratio
var aspect = originalWidth / (float)originalHeight;
int newWidth, newHeight;
var dimenssionTooSmall = false;
if (originalWidth <= originalHeight && originalWidth < 100)
{
//calculate new dimensions based on aspect ratio
newHeight = (int)(100 / aspect);
var resizeLayer = new ResizeLayer(new Size(100, newHeight), ResizeMode.Min);
imageProcessor.Resize(resizeLayer);
dimenssionTooSmall = true;
}
else if (originalHeight < originalWidth && originalHeight < 100)
{
//calculate new dimensions based on aspect ratio
newWidth = (int)(100 / aspect);
var resizeLayer = new ResizeLayer(new Size(newWidth, 100), ResizeMode.Min);
imageProcessor.Resize(resizeLayer);
dimenssionTooSmall = true;
}
if (byteCuantity > 1 || dimenssionTooSmall)
{
//format.Quality = 6;
imageProcessor.Resize(new ResizeLayer(new Size(3840, 2160), ResizeMode.Min));
imageProcessor.Format(format);
imageProcessor.Save(outStream);
return outStream.ToArray();
}
else
{
return inStream.ToArray();
}
}
}
}
}
}
谢谢并恭祝安康。