【发布时间】:2016-08-10 08:54:19
【问题描述】:
我有一个 MVC 应用程序,您可以在其中上传图片并将其大小调整为最大。 50KB。 我在while循环中调整大小,但问题是当我减小图片的宽度和高度时,文件大小会增加。在某个时候,尺寸会变小,但会以质量为代价
Request.InputStream.Position = 0;
string Data = new System.IO.StreamReader(Request.InputStream).ReadToEnd();
var Base64 = Data.Split(',')[1];
var BitmapBytes = Convert.FromBase64String(Base64);
var Bmp = new Bitmap(new MemoryStream(BitmapBytes));
while (BitmapBytes.Length > 51200)
{
int Schritte = 20; //I tested here also with 300
int maxWidth = Bmp.Width;
maxWidth = maxWidth - Schritte;
int maxHeight = Bmp.Height;
maxHeight = maxHeight - Schritte;
Bmp = ScaleImage(Bmp, maxWidth, maxHeight);
var base64 = ReturnImageAsBase64(Bmp);
BitmapBytes = Convert.FromBase64String(base64);
}
调整大小的代码:
public static Bitmap ScaleImage(Image image, int maxWidth, int maxHeight)
{
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
Bitmap newImage = new Bitmap(newWidth, newHeight);
using (Graphics gr = Graphics.FromImage(newImage))
{
gr.SmoothingMode = SmoothingMode.HighQuality;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
gr.DrawImage(image, new Rectangle(0, 0, newWidth, newHeight));
}
return newImage;
}
我从 66964 字节的大小开始。在循环的第一轮之后,它的 85151 字节虽然宽度减少了 300 像素,高度减少了 420 像素。
【问题讨论】:
-
我会说这是您的 Pixelformat 的问题。例如,如果您有一个 1bpp(黑色或白色)的位图并将其绘制到 ScaleImage 中的 newImage 中,则 newImage 是使用可能使用 Colors 的默认 Pixelformat 创建的,因此您最终会得到 24bpp,这会导致更高的内存大小.