Apr 5, 2010 at 12:56 AM
Edited Apr 5, 2010 at 12:58 AM
Below is the GetXImageFromBitmap function I created to get a PNG from WriteableBitmap using the ImageTools Silverlight SDK and then convert it into an XImage.
The ms variable is good and there's data there. But it fails eventually with "The byte array is not a recognized imageformat" error once the FromStream method is run.
After tracing the code, it seems to fail on this chunk in of code (in the file
\!compatebleLayer\StreamHelper.cs ) where the conversion to memory stream just returns 0bytes in the byte array.
Any idea how to fix this?
public static class StreamHelper
public static MemoryStream CloneToMemoryStream(this Stream obj)
var m = new MemoryStream();
var bytes = new byte[obj.Length];
obj.Read(bytes, 0, bytes.Length);
return new MemoryStream(bytes); // bytes is full of 0s!!!!!
Here's my function:
public static XImage GetXImageFromBitmap(WriteableBitmap bitmap)
int imageData = bitmap.Pixels;
byte bytes = new byte[imageData.Length * 4];
int offset = 0;
// The writeable bitmap pixel format is ARGB while ImageTools uses RGBA so we need to convert
foreach (int pixel in imageData)
bytes[offset] = (byte)(pixel >> 16);
bytes[offset + 1] = (byte)(pixel >> 8);
bytes[offset + 2] = (byte)(pixel >> 0);
bytes[offset + 3] = (byte)(pixel >> 24);
offset += 4;
// Set pixel on image
Image img = new Image();
img.SetPixels(bitmap.PixelWidth, bitmap.PixelHeight, bytes);
// Encode the image to a memory stream and return it
PngEncoder encoder = new PngEncoder();
MemoryStream ms = new MemoryStream();
I believe I know why this isn't working.
It seems non-interlaced PNG file is not well handled.
I looked at the PNG samples that come with Test projects and noticed they were Interlaced; the ones I was testing were Non-interlaced.
Saving the Test PNGs to non-interlaced caused the same error.
Anyone have a workaround?
Jul 10, 2010 at 4:31 PM
Edited Jul 10, 2010 at 4:32 PM
1) Convert WritableBitmap to Steam, using this library
2) Then just load this image to your PDF using XImage.LoadFromSteam method