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...

9
  • Question: is your input a jpeg and your output a bmp? Commented Nov 6, 2017 at 19:01
  • Both are JPG files Commented Nov 6, 2017 at 19:02
  • Thats odd, because when I do some math: 2847 x 2125 x 24bpp I get approx. 17 MB. So, you might be saving as a jpeg file, the file size suggest it's a bmp. Commented Nov 6, 2017 at 19:04
  • Maybe this will give some more info: stackoverflow.com/questions/21218017/… Commented Nov 6, 2017 at 19:07
  • 1
    seeing a ".jpg" extension doesn't mean this file is in jpeg format. use newImage.Save(newPath, ImageFormat.Jpeg) Commented Nov 6, 2017 at 19:18

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.