0

I have some images that have more than, let's say 6.000.000 pixels and I want to scale them to be somewhere around that value.

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);
        }
    }

I've tried to downscale an image that had 6367 x 4751 pixels and 72 dpi resolution (24 bit depth) with the size of 8.03 MB. I've resized this image and I was expecting to be a much more smaller one in size (bellow 8 MB) but mine has 17. The scaled image is 2847 x 2125 (96 dpi with 32 Bit depth). Why is this happening? Is there a way to downscale an image to a requested number of pixels and the result to have the size much more smaller? I don't care about the resolution...

Dana
  • 1,788
  • 3
  • 21
  • 51

1 Answers1

1

You are using integer division and truncating results at:

inSampleSize = Math.Sqrt(actualNumberofPixels / reqNumberOfPixels);

Try instead:

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

Also, save with:

newImage.Save(newPath, ImageFormat.Jpeg);

As the sizes you are getting seem much too large if you are saving with a lossy format with that many pixels

Ehz
  • 1,962
  • 1
  • 11
  • 11