我使用下面编写的代码来缩小图像大小并保持宽高比。我调整大小的图像是1920 * 1275 1.9mbytes,原始图像大小是4288×2848 1.8mbytes。图像大小已调整大小但文件大小未调整。我如何减小文件大小?
目前,我想保持图像的质量。
var sourceImage = new UIImage(source);
var sourceSize = sourceImage.Size;
var maxResizeFactor = Math.Max(targetWidth / sourceSize.Width, targetHeight / sourceSize.Height);
if (maxResizeFactor > 1) return source;
var ratioImage = sourceSize.Width / sourceSize.Height;
var ratioScreen = targetWidth / targetHeight;
var newWidth = 0.0f;
var newHeight = 0.0f;
if (ratioScreen > ratioImage)
{
newWidth = (float)(sourceSize.Width * (targetHeight / sourceSize.Height));
newHeight = targetHeight;
}
else
{
newWidth = targetWidth;
newHeight = (float)(sourceSize.Height * (targetWidth / sourceSize.Width));
}
UIGraphics.BeginImageContext(new SizeF((float) newWidth, (float) newHeight));
sourceImage.Draw(new RectangleF(0, 0, (float)newWidth, (float)newHeight));
var resultImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
NSError error;
if (MimeType.IsPNG(source))
resultImage.AsPNG().Save(destination, true, out error);
else
resultImage.AsJPEG().Save(destination, true, out error);
if (error != null)
return source;
else
return destination;