king yau king yau - 2 months ago 7
C# Question

Why my BMP image is bigger than the original after reducing its width and height?

In my project, i have to resize the image and then save it to a folder. However, i got a problem which some image will be bigger than the orginal's file size.

resize method:

public Image reduce(Image sourceImage, string size)
{
double percent = Convert.ToDouble(size) / 100;
int width = (int)(sourceImage.Width * percent);
int height = (int)(sourceImage.Height *percent );
var resized = new Bitmap(original, width, height);
return resized;
}


using:

//the code to get the image is omitted (in my testing, bmp format is fixed, however, other image formats are required)
//to test the size of original image
oImage.Save(Path.Combine(oImagepath), System.Drawing.Imaging.ImageFormat.Bmp);

Image nImage = resizeClass.reduce(oImage,"95");
nImage.Save(Path.Combine(nImagepath), System.Drawing.Imaging.ImageFormat.Bmp);


Result:



  • The first saving of the image: 1920*1080, fileSize: 6076KB

  • The second saving of the image: 1824*1026, fileSize: 7311KB <= it should be less than 6076KB




Image:



Update

The Bit depth of original image is 24 which resized is 32. Is the problem here?

Answer

Based on your provided Code, i've made an ExtensionMethod you might want to use:

public static class ImageExtensions {

    public static System.Drawing.Image Reduce(this System.Drawing.Image sourceImage, double size) {
      var percent = size / 100;
      var width = (int)(sourceImage.Width * percent);
      var height = (int)(sourceImage.Height * percent);         
      Bitmap targetBmp;
      using (var newBmp = new Bitmap(sourceImage, width, height))
        targetBmp = newBmp.Clone(new Rectangle(0, 0, width, height), sourceImage.PixelFormat);
      return targetBmp;
    }

  }

Usage

 var nImage = new Bitmap(@"PathToImage").Reduce(50); //Percentage here
 nImage.Save(@"PathToNewImage", ImageFormat.Jpeg); //Change Compression as you need

Please note, that this is now automaticly determinating, where the new Image has its x = 0 and y = 0. Also i've replaced the string-percentage with a double one.

As others in the comments mentioned, you have to use the same or even lower PixelFormat as the SourceImage. Also, setting the right/best image-extension on the Save-Method reduces the FileSize

Hope this helps