【发布时间】:2017-08-18 11:22:26
【问题描述】:
我一直在使用这种方法将上传的.JPG 图像调整为最大宽度,但这会导致图像以 kb 为单位大于源图像。我究竟做错了什么?保存新图像时我还需要做些什么吗?
我尝试了PixelFormat 的各种组合,例如PixelFormat.Format16bppRgb555
例如:源图像是.JPG 1900w,正在尝试将大小调整为 1200w...
- 源文件为 563KB,
- 调整后的文件为 926KB 或更大,甚至 1.9MB
public static void ResizeToMaxWidth(string fileName, int maxWidth)
{
Image image = Image.FromFile(fileName);
if (image.Width > maxWidth)
{
double ratio = ((double)image.Width / (double)image.Height);
int newHeight = (int)Math.Round(Double.Parse((maxWidth / ratio).ToString()));
Bitmap resizedImage = new Bitmap(maxWidth, newHeight);
Graphics graphics = Graphics.FromImage(resizedImage);
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High
Rectangle rectDestination = new Rectangle(0, 0, maxWidth, newHeight);
graphics.DrawImage(image, rectDestination, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
graphics.Dispose();
image.Dispose();
resizedImage.Save(fileName);
resizedImage.Dispose();
}
image.Dispose();
}
【问题讨论】:
-
您使用的是 jpg 文件吗?你说的是磁盘大小吗?它用于 jpg 主要由编码质量设置决定。您应该添加一个显式编码器来控制它!
-
我已经编辑了我的问题,以反映我主要上传 jpg。有的话请加个答案谢谢!
-
位图类不检测文件扩展名的格式。您可能会将其保存为带有 jpeg 文件扩展名的 png 格式。您需要将第二个参数提供给 save 方法。
-
@john 天哪,我什至不知道有第二个参数的选项!添加 ImageFormat.JPEG 立即解决了这个问题!你能添加一个答案吗?
-
@Dave 如果 TaW 没有决定将您的问题错误地标记为重复,我将能够做到。可悲的是他做到了,所以我不能。
标签: c# image-resizing filesize pixelformat