Search code examples
c#bitmapmemorystreamsystem.drawing.imaging

Bitmap.Save erroring with Null Exception and yet it is clearly instantiated


Before an upgrade to Unity and Visual Studio I had a simple block of code that ran without errors, after the updates however the exact same logic raises a NullReferenceException.

The exception is raised when calling BitMap.Save() but I have verified that all the inputs are appropriately instantiated and I can inspect all the associated objects during debug and cannot identify any nulls. In this case the NullReferenceException is very ambiguous and I suspect it is linked specifically to the update to Unity.

Please do not close for duplicate of "What is a NullReferenceException, and how do I fix it?" like my other one. This seems to be an internal issue either with Bitmap and I am looking for specific guidance on how to resolve this.

Bitmap newBmp = new Bitmap(16, 16);
for (int i= 0; i< 16; i++)
{
    for (int j= 0; j< 16; j++)
    {
         newBmp.SetPixel(i, j, Color.blue);
    }
}
using (MemoryStream ms = new MemoryStream())
{
    newBmp.Save(ms, ImageFormat.Bmp); // Null??
    // do more stuff with ms if it didn't crap out
}

Exception Detail, raised on newBmp.Save()

NOTE: neither newBmp or ms are null, and the logic above it has set each pixel to the color blue.

NullReferenceException: Object reference not set to an instance of an object
System.Drawing.ComIStreamMarshaler+ManagedToNativeWrapper..cctor () (at <556bd4f081384ff9b1658a316bdf6616>:0)
Rethrow as TypeInitializationException: The type initializer for 'ManagedToNativeWrapper' threw an exception.
System.Drawing.ComIStreamMarshaler.MarshalManagedToNative (System.Object managedObj) (at <556bd4f081384ff9b1658a316bdf6616>:0)
System.Drawing.Image.Save (System.IO.Stream stream, System.Drawing.Imaging.ImageCodecInfo encoder, System.Drawing.Imaging.EncoderParameters encoderParams) (at <556bd4f081384ff9b1658a316bdf6616>:0)
System.Drawing.Image.Save (System.IO.Stream stream, System.Drawing.Imaging.ImageFormat format) (at <556bd4f081384ff9b1658a316bdf6616>:0)
(wrapper remoting-invoke-with-check) System.Drawing.Image.Save(System.I

Solution

  • It turned out that my version of System.Drawing.dll which I pulled into my Unity project a while back, was not compatible with the new version of Unity. We solved it by removing the dll and adding a "csc.rsp" file to the Assets folder and added the line -r:System.Drawing.dll which, I presume, automatically uses the appropriate version.