Search code examples
c#imageimage-resizing

Resizing image in C# - null exception?


I'm trying to resize an image if it's wider than x to fit it into a Word Document, but I'm getting a following error message:

An exception of type 'System.ArgumentNullException' occurred in System.Drawing.dll but was not handled in user code

Additional information: Value cannot be null.

 using (MemoryStream ms = new MemoryStream())
            {
                System.Drawing.Image image = System.Drawing.Image.FromFile(physicalPath);
                System.Drawing.Image resizedImage;

                if (image.Width > 650)
                {
                    double multiplier = image.Width/650.0;
                    int newWidth = 650;
                    int newHeight = (int) (image.Height/multiplier);
                    resizedImage = (System.Drawing.Image)new Bitmap(image, new Size(newWidth,newHeight));
                }
                else
                {
                    resizedImage = image;
                }

                image.Dispose();
                resizedImage.Save(ms, resizedImage.RawFormat);
}

Error occures while executing resizedImage.Save(..) method. I debugged the code and neither resizedImage nor ms nor RawFormat property of resizedImage are null. What am I doing wrong?

This works ok for images with Width less or equal 650.


Solution

  • You can't save using RawFormat unless the file comes from an existing file (resizedImage is an in-memory bitmap, unlike image).

    Use a specific format for saving (for example: ImageFormat.Png, or ImageFormat.Jpeg), or use image.RawFormat instead of resizedImage.RawFormat if you want to save using the original's file format