我有一个函数,它接收图像数据的字节数组,然后调整它的大小,使其高度和/或宽度最大约为 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 "";
}
谁能解释为什么文件大小因尺寸减小而急剧增加以及如何防止它(或实际上除了减小文件尺寸外还减小文件大小)?