c# - 在尺寸减小时防止图像尺寸增大
问题描述
我有一个函数,它接收图像数据的字节数组,然后调整它的大小,使其高度和/或宽度最大约为 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 "";
}
谁能解释为什么文件大小因尺寸减小而急剧增加以及如何防止它(或实际上除了减小文件尺寸外还减小文件大小)?
解决方案
您将其保存为 .bmp,文件大小会大得多。
将该行更改new_image.Save(m, ImageFormat.Bmp);
为new_image.Save(m, ImageFormat.Png);
or new_image.Save(m);
,这会将其保存为 .png 而不是未压缩的 .bmp(后者默认选择 .png 格式)。
有关更多信息,请参阅Image.Save文档。
推荐阅读
- c# - 使用 Linq Select 时出现 ArgumentNullException
- c - 如何使用结构在 C 中使用函数指针?
- c# - 恢复数据库 PostgreSQL 重复行
- gmail-api - gmail过滤器中是否有选择转发和抄送地址的功能?
- java - 如何在 Spring Security 中启用基本授权?
- azure-devops - 如何从 Git Hub 持续更新 azure repo?
- excel - Excel - 如何在大量数值数据中找到匹配行的模式?
- ionic-framework - 键盘隐藏屏幕
- linux - 如何压缩环境变量中非常长的文件列表:***检测到缓冲区溢出***:zip终止
- php - Tooltipster 工具提示未在点击触发器上打开