【发布时间】:2016-05-12 23:13:16
【问题描述】:
我想要减小图像大小的功能。
该函数应获取图像 URL,检查图像大小为 4MB 或更大,如果是则将其调整为情人然后 4MB 并返回字节。
我有下一个方法:
public byte[] ResizeImage(string url)
{
var uri = new Uri(url);
var c = new WebClient();
var oldImgStream = new MemoryStream(c.DownloadData(uri));
if (oldImgStream.Length <= 4194304)
{
return oldImgStream.ToArray();
}
using (var oldImage = new Bitmap(oldImgStream))
using (var newImageStream = new MemoryStream())
{
var format = oldImage.RawFormat;
float resizePercent = (float)4194304 / oldImgStream.Length;
var newImage = ResizeImageByPercent(oldImage, resizePercent);
newImage.Save(newImageStream, format);
return newImageStream.ToArray();
}
}
public static Bitmap ResizeImageByPercent(Bitmap image, float resizePercent)
{
//Set minimum resizePercentage to 80%
resizePercent = resizePercent > 0.8 ? (float)0.8 : resizePercent;
int newWidth = (int)(image.Width * resizePercent);
int newHeight = (int)(image.Height * resizePercent);
var newImage = new Bitmap(newWidth, newHeight);
using (var graphics = Graphics.FromImage(newImage))
{
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
graphics.FillRectangle(Brushes.Transparent, 0, 0, newWidth, newHeight);
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
return newImage;
}
}
但这并不好。
我有一个 jpg 图像作为示例。
图像大小略大于 4MB(4194587 字节)。 图像分辨率为 2272 x 1704。
因此,当我尝试使用上述方法调整此图像的大小时。 它首先计算“resizePercentage”为:
float resizePercent = (float)4194304 / oldImgStream.Length;
resizePercent = (float)4194304 / 4194587;
resizePercent = 0.9999325 //(99.99325%)
但是因为我设置了最小的 resizePercent,它将被设置为 0.8 (80%)。
resizePercent = 0.8;
然后它会用这个 resizePercent 计算新的宽度和高度。
新的分辨率将是:1817 x 1363 并且图像被调整为新的分辨率。 但是在将其保存到流并读取字节后,它会返回更大的图像。 返回图像的站点是“5146056 字节”5MB
那么有没有人知道如何实现这一点,或者我的方法有什么问题,所以即使分辨率降低,它也会返回更大的图像。
我应该能够缩小图像 png、jpg 和 gif 的大小
【问题讨论】:
-
您在接收图像时不知道所应用的 jpg 压缩的质量。因此,也许您正在以比原始图像更高的质量(即压缩更少)保存图像。使用 bmp 图像时问题是否仍然存在?
-
如果您的测试图像是 JPEG,它的压缩率可能高于 .NET 默认使用的压缩率。由于 JPEG 使用有损压缩,因此有多种可用的压缩比;他们将确定生成的图像看起来有多粗糙。对于无损的 PNG,原始图像仍然有可能通过比 .NET 使用的更好的算法进行压缩。以此类推。
标签: c# asp.net-mvc image bitmap memorystream