2

I am trying to convert a grayscale Bitmap (Format16bppGrayScale) to a color Bitmap (Format32bppArgb) like so:

Bitmap color = gray.Clone(new Rectangle(0, 0, gray.Width, gray.Height), PixelFormat.Format32bppArgb);

I keep getting a System.OutOfMemoryException. I have been researching and this error usually occurs when the rectangle provided to Clone is bigger than the actual image that you are trying to clone. This is not the case here since I am using the image dimensions to create the rectangle. Are there known issues with this type of conversions? Are there any other ways to achieve a copy in a different PixelFormat?

Thanks,

Pol
  • 306
  • 2
  • 12
  • What are dimensions of your image? – Alexei Levenkov Feb 03 '16 at 23:26
  • the image is 628x468 – Pol Feb 03 '16 at 23:49
  • 2
    Just do this with a 1x1 bitmap. And you'll find the usual problem with GDI+ exceptions, they are **very** misleading. This just isn't supported, 16bppGrayScale is the kind of format you'll find used in your hospital's radiological imaging department. The cost of the hardware is included with the bill. Backgrounder answer [is here](http://stackoverflow.com/questions/2610416/is-there-a-reason-image-fromfile-throws-an-outofmemoryexception-for-an-invalid-i/2610506#2610506) – Hans Passant Feb 03 '16 at 23:54
  • Are there any workarounds? The image I am getting is actually from a depth camera. – Pol Feb 04 '16 at 00:29

1 Answers1

0

I read, people have problem like you. Try this way: Change PixelFormat, while you try clone, system have problem. Biggest reason is new definition of Bitmap.

Bitmap clone = new Bitmap(gray.Width, gray.Height, PixelFormat.Format32bppArgb);
using (Graphics gr = Graphics.FromImage(clone)) {
        gr.DrawImage(color, new Rectangle(0, 0, clone.Width, clone.Height));
}

Or without DrawImage function:

using (Bitmap color = gray.Clone(new Rectangle(0, 0, gray.Width, gray.Height), PixelFormat.Format32bppArgb))
{
    // color is now in the desired format.
}
Nejc Galof
  • 2,538
  • 3
  • 31
  • 70
  • 2
    Thanks neiiic, I tried both suggestions and I still get the same out of memory error... – Pol Feb 03 '16 at 23:49