2

Don't know a whole lot about streams. Why does the first version work using a file but the second does not? Putting a breakpoint on "return dest;" it looks like both have created exactly the same thing but dest is always a blank image using the second version.

    public static BitmapSource ConvertByteArrayToBitmapSource(Byte[] imageBytes, ImageFormat formatOfImage)
{
    BitmapSource dest = null;
    if (formatOfImage == ImageFormat.Png)
    {
        var streamOut = new FileStream("tmp.png", FileMode.Create);
        streamOut.Write(imageBytes, 0, imageBytes.Length);
        streamOut.Close();

        Uri myUri = new Uri("tmp.png", UriKind.RelativeOrAbsolute);
        var bdecoder2 = new PngBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
        dest = bdecoder2.Frames[0];
    }

    return dest;
}

public static BitmapSource ConvertByteArrayToBitmapSource_NoWork(Byte[] imageBytes, ImageFormat formatOfImage)
{
    BitmapSource dest = null;
    using (var stream = new MemoryStream(imageBytes))
    {
        var bdecoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
        stream.Flush();
        dest = bdecoder.Frames[0];
        stream.Close();
    }

    return dest;
}
strattonn
  • 1,790
  • 2
  • 22
  • 41
  • Why do you call Flush ? Does it work without it? – Thomas Levesque Jun 15 '11 at 21:26
  • Why would you use a specific decoder if you can directly create a [`BitmapImage`](http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.aspx) from stream instead? – H.B. Jun 16 '11 at 00:04
  • Flush or no flush doesn't work. I need a BitmapSource not a BitmapImage. Basically I am saving the value from a BitmapSource to a db as array[] then restoring it back as a BitmapSource. – strattonn Jun 16 '11 at 12:40

1 Answers1

8

You have to specify BitmapCacheOption.OnLoad as the bitmap will otherwise be loaded when its displayed for the first time. Then, however, the stream is already disposed.

Also, take at look at this version supporting different image formats and freezing the image for better performance:

public static BitmapSource ConvertByteArrayToBitmapSource(Byte[] imageBytes)
{
    using (MemoryStream stream = new MemoryStream(imageBytes))
    {
        BitmapDecoder deconder = BitmapDecoder.Create(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
        BitmapFrame frame = deconder.Frames.First();

        frame.Freeze();
        return frame;
    }
}
Matthias
  • 12,053
  • 4
  • 49
  • 91