C# – “A generic error occurred in GDI+” when saving Bitmap object as jpeg, c#


I have an array of ushort pixel data (16-bit grayscale values), and I am trying to save it as a jpeg image. However my code is crashing at the Save command with "A generic error occurred in GDI+". I can't figure out how to fix this. The directory I am saving to is created by my application and I write other files to it; so I know it's not a permissions problem. Is it maybe a data corruption problem? Am I doing something wrong in the steps to get the ushort data into the Bitmap object? Because I have ushort data I found it took some effort to figure out how to get it into the Bitmap object, and I am possibly doing it wrong.

Here is my code:

Bitmap img = new Bitmap(width, height, PixelFormat.Format16bppGrayScale);
Rectangle rect = new Rectangle(0,0, width, height);
BitmapData picData = img.LockBits(rect, ImageLockMode.ReadWrite, img.PixelFormat);
IntPtr pixelStartAddress = picData.Scan0;

WriteableBitmap pic = new WriteableBitmap(width, height, 96.0, 96.0, System.Windows.Media.PixelFormats.Gray16, null);

int stride = (thumb.XSize * pic.Format.BitsPerPixel + 7) / 8;
pic.WritePixels(new System.Windows.Int32Rect(0, 0, width, height), dataArray, stride, 0);  

pic.CopyPixels(new System.Windows.Int32Rect(0,0,thumb.XSize, thumb.YSize),pixelStartAddress, dataArray.Length * sizeof(ushort), stride);

img.Save(path, ImageFormat.Jpeg);

This whole thing has become very frustrating. Please help?!

Best Solution

I'm, afraid it has something to do with the grayscale / JPG. I don't know if JPEG supports grayscales.

I would try declaring the bitmap as a normal color one. And testing.

Related Question