This project is read-only.

Creating WriteableBitmapEx from 16 bit array of raw pix data.

May 19, 2011 at 7:36 PM

Is WritableBitmapEx a good choice to programmatically create a source for Silverlight Image from ushort[] pixel array that came from an image acquisition device?


ushort[] pixels - 2 bytes per pixel, 512x512 pixels array.  total of 262144 pixels all together.

Then the code should be somthing like this:

WriteableBitmap wb = new WriteableBitmap(512, 512);
for(int y = 0 ; y < 512; y++)
   for (int x=0; x < 512;x++)
      wb.SetPixel(x,y, _color); // here is the question: how to place my pixel[x*y] value into SetPixel??

As well, if we have a 2 byte per pixel should we allocate 512 * 2 per line?

Thanks a lot for help.

May 19, 2011 at 8:21 PM

WB uses pARGB (4 bytes per pixe)l, so you need to convert your 2 byte color data into this. It depends what these 2 bytes mean. Your destination pixel is ARGB (alpha, red, green, blue).

May 20, 2011 at 12:32 AM

The 2 bytes are the ushort of each pixel value of 0 - 65K range.  If I got you right, the WB has each pixel described by 4 bytes of ARGB.  So far so good.

If I allocate new WriteableBitmap(512, 512), I actually allocate 512 x 512 x 4, right?  If you confirm, then I need to convert my ushort pixel value to byte and do something like below in my for loop:


pixel = wb.Pixels[y * wb.PixelWidth + x];


byte[] d = BitConverter.GetBytes(pixel);

d[0] = ushortPixel2Byte(ushort pixvalue);



 //last convert it back to my wb

wb.Pixels[y * wb.PixelWidth + x] = BitConverter


.ToInt32(d, 0);

 //end of for loop


Did I get your suggestion right?

d[1] = d[0];//all the same for grey scale bitmap

d[2] = d[0];

d[3] = d[0];

May 20, 2011 at 8:30 AM
Edited May 20, 2011 at 8:31 AM

You have to extract the red, green and blue color info from the ushort using some bit fiddling (SHIFT, AND, OR, ...) or is it a gray value? Then you can assign the value to the WB.


// Important. Save some cycles in the loop by avoiding the call of the property 
int[] p = wb.Pixels;

for(int i=0; i< p.Length; i++)
   // r, g, b are single byte values filled with the appropriate color.
   p[i] = (255 << 24) | (r << 16) | (g << 8) | b;