C#将图像缩小到一定数量的像素

时间:2017-11-06 18:57:57

标签: c# image rescale

我有一些图像超过,让我们说6.000.000像素,我想将它们缩放到该值附近。

public void downscaleByCalculateInSampleSize(string filePath, string newPath)
    {
        int reqNumberOfPixels = 6000000;

        double inSampleSize = 1;

        using (System.Drawing.Image oImage = System.Drawing.Image.FromFile(filePath))
        {
            int newWidth = oImage.Width;
            int newHeight = oImage.Height;

            int actualNumberofPixels = oImage.Width * oImage.Height;

            if (actualNumberofPixels > reqNumberOfPixels)
            {
                inSampleSize = Math.Sqrt(actualNumberofPixels / reqNumberOfPixels);

                newWidth = Convert.ToInt32(Math.Round((float)oImage.Width / inSampleSize));
                newHeight = Convert.ToInt32(Math.Round((float)oImage.Height / inSampleSize));
            }

            var newImage = new Bitmap(newWidth, newHeight);

            Graphics graphics = Graphics.FromImage(newImage);

            graphics.DrawImage(oImage, 0, 0, newWidth, newHeight);

            newImage.Save(newPath);
        }
    }

我试图缩小具有6367 x 4751像素和72 dpi分辨率(24位深度)且大小为8.03 MB的图像。我已经调整了这个图像的大小,我希望它的尺寸​​要小得多(低于8 MB)但是我有17个。缩放图像是2847 x 2125(96 dpi,32位深度)。为什么会这样? 有没有办法将图像缩小到所需的像素数,结果是尺寸要小得多?我不关心决议......

1 个答案:

答案 0 :(得分:1)

您正在使用整数除法和截断结果:

inSampleSize = Math.Sqrt((double)actualNumberofPixels / (double)reqNumberOfPixels);

尝试改为:

newImage.Save(newPath, ImageFormat.Jpeg);

另外,保存时间:

COUNT(*) OVER(...)

如果您使用带有那么多像素的有损格式进行保存,那么您获得的尺寸似乎太大了