.Net C# A generic error occurred in GDI+.

I get this error when converting a Bitmap image to a byte array. This code is used in both a desktop application and windows services and I only get the error while using the method in a service.

What Am I doing wrong?

            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(OutImgInfo.Width, OutImgInfo.Height, pFormat);

            //Create a BitmapData and Lock all pixels to be written   
            System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, bmp.PixelFormat);

            //Copy the data from the byte array into BitmapData.Scan0   
            Marshal.Copy(NewArray, 0, bmpData.Scan0, NewArray.Length);

            //Unlock the pixels   

            // Need to remove GDI+ generic errors
            //System.Drawing.Bitmap tempBmp = new System.Drawing.Bitmap(bmp);

            using (MemoryStream ms = new MemoryStream() )
		                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Tiff);
                    catch (SystemException)

                //Return the byte[]
                return ms.GetBuffer().ToArray<byte>();

Open in new window

Who is Participating?
csalernoConnect With a Mentor Author Commented:
My code, above the snippet, was not supporting 8-bit image format. I added the below instead of it falling thru to the default and the error was corrected.

                case 8:
                    pFormat = System.Drawing.Imaging.PixelFormat.Format8bppIndexed;
                    pFormat = System.Drawing.Imaging.PixelFormat.Format16bppGrayScale;
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.