【问题标题】:Resize image to lowest size with minimum quality loss以最小的质量损失将图像调整为最小尺寸
【发布时间】:2020-06-01 16:03:22
【问题描述】:

我有这段代码可以调整图片大小:

public static void GetProductSmallThumbnail(string fileUrl, string fileName)
        {
            System.Drawing.Image.GetThumbnailImageAbort myCallback =
            new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);

            System.Drawing.Image img = null;
            FileStream fs = null;
            try
            {
                fs = new FileStream(fileUrl, FileMode.Open, FileAccess.Read);
                img = System.Drawing.Image.FromStream(fs);
                int orgwidth = img.Width;
                int orgheight = img.Height;

                int imgwidth = img.Width;
                int imgheight = img.Height;

                // if 240 is max width
                imgwidth = 240;
                imgheight = Convert.ToInt32((imgwidth * orgheight) / orgwidth);
                System.Drawing.Image myThumbnail = img.GetThumbnailImage(
                imgwidth, imgheight, myCallback, IntPtr.Zero);
                myThumbnail.Save(Path.Combine(Directory.GetCurrentDirectory(), "assets/products/small/" + fileName + ".jpg"));
            }
            finally
            {
                fs.Close();
            }

        }

一切正常,但文件大小超出预期。 例如,我将此图像用于输入:

生成的图像具有正确的宽度和高度,但大小为 89 KB,但我希望此图像为 7 KB

【问题讨论】:

  • @michasaucer 无论如何都不会将其保存为 JPG 吗?
  • OP,你确认myThumbnail.Save(确实生成了一个jpeg文件吗?
  • 亲爱的@michasaucer 我该怎么做?
  • 在我自己的测试中,您的代码生成了一个带有 .JPG 文件扩展名的 PNG 文件。
  • 哦!如何纠正?

标签: c#


【解决方案1】:

System.Drawing.ImageSave 函数有一个重载,它接受格式作为其第二个参数(请参阅docs)。要以不同于原始格式的格式保存图像,请将格式传递给保存函数:

myThumbnail.Save(
    Path.Combine(Directory.GetCurrentDirectory(), "assets/products/small/" + fileName + ".jpg"),
    ImageFormat.Jpeg);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多