我有一个函数,它接收图像数据的字节数组,然后调整其大小,以便其高度和/或宽度最大为200px。
该功能成功地减小了图像的尺寸(以尺寸为单位),但是文件的尺寸却大大增加了。
示例: 调整了原始大小为32.2KB的图像,尺寸为828x251。 输出为374KB的图像,尺寸为577x200。
下面是正在使用的函数:
public static string resizeImage(string imgToResize)
{
try
{
string image_info = imgToResize.Split(',')[0];
MemoryStream ms = new MemoryStream(Convert.FromBase64String(imgToResize.Split(',')[1]));
System.Drawing.Image converted_image = System.Drawing.Image.FromStream(ms);
int original_width = converted_image.Width;
int original_height = converted_image.Height;
// Figure out the ratio
double ratioX = (double) original_width / (double) original_height;
double ratioY = (double) original_height / (double) original_width;
// use whichever multiplier is smaller
double ratio = ratioX < ratioY ? ratioX : ratioY;
int new_height = 0;// Convert.ToInt32(original_height * ratio);
int new_width = 0;// Convert.ToInt32(original_width * ratio);
// now we can get the new height and width
if (original_width <= original_height)
{
new_width = 200;
new_height = Convert.ToInt32((decimal)new_width / (decimal)ratio);
}
else {
new_width = Convert.ToInt32((decimal)original_width * (1-(decimal)ratio));
new_height = 200;
}
Size image_size = new Size(new_width, new_height);
System.Drawing.Image new_image = (System.Drawing.Image)(new Bitmap(converted_image, image_size));
using (MemoryStream m = new MemoryStream())
{
new_image.Save(m, ImageFormat.Bmp);
byte[] imageBytes = m.ToArray();
string base64String = Convert.ToBase64String(imageBytes);
return image_info + "," + base64String;
}
}
catch (Exception ex) {
ErrorSignal.FromCurrentContext().Raise(ex);
}
return "";
}
有人能解释为什么文件大小因这种减小而急剧增加,以及如何防止(或者除了减小文件大小之外实际上减小文件的大小)?
答案 0 :(得分:1)
您正在将其另存为.bmp,这将具有更大的文件大小。
将行new_image.Save(m, ImageFormat.Bmp);
更改为new_image.Save(m, ImageFormat.Png);
或new_image.Save(m);
,这会将其保存为.png而不是未压缩的.bmp(默认情况下,后者选择.png格式)。
有关更多信息,请参见Image.Save文档。