图像大小调整导致文件大小比原始 C# 大得多
Image resize results in massively larger file size than original C#
我一直在使用这种方法将上传的 .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();
}
您需要指定保存为jpeg格式:
resizedImage.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
否则会默认保存为BMP/PNG(我不记得是哪个了)。
我一直在使用这种方法将上传的 .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();
}
您需要指定保存为jpeg格式:
resizedImage.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
否则会默认保存为BMP/PNG(我不记得是哪个了)。