c# - 图像大小调整导致文件大小比原始 C# 大得多

标签 c# image-resizing filesize pixelformat

我一直在使用这种方法将上传的 .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(我不记得是哪个)。

关于c# - 图像大小调整导致文件大小比原始 C# 大得多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43017831/

相关文章:

c# - 为什么 Convert.ToInt32() 舍入到最接近的偶数,而不是最接近的整数?

c# - 新 MVC3 项目中的 InversionOfControl

c# - C# 中是否有任何紧凑而优雅的方法来同时遍历两个列表?

php - 检查 ZIP 存档中内容的文件大小

c# - 验证仅适用于数组的第一项

iphone - 响应式 img 调整大小在 iPad 上不起作用

css - bootstrap - 保持 IMG 大小相同并以 XS 为中心

Python:如何使用 PIL 模块调整图像大小

php循环文件夹获取文件名和大小

android - 如何获取已安装应用程序的大小?