• 0

[C#] Binding image to memorystream, how does it not create a memory leak?


Question

Maybe the method I am using is one of bad practice. I'm going to assume there is a better way of doing it. I have an image bound to a byte array (that will be designated by a byte array in a database but that is outside of the scope of this topic). The thing is it creates a memory stream but I can not close the memory stream and properly dispose of it because the image will no longer show since the memorystream will become unreadable/unusable.


public sealed class ImageIconConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            byte[] buffer = (value as byte[]);
            if (buffer == null)
                return null;
            MemoryStream mStream = new MemoryStream(buffer);
            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            bi.StreamSource = mStream;
            bi.EndInit();

            /*mStream.Close();
            mStream.Dispose();
            mStream = null;*/ <---------------- can not use these lines, if I do the image will not show because the memory stream will become unusable.
            return bi;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            BitmapImage bi = (value as BitmapImage);
            byte[] buffer = new byte[bi.StreamSource.Position - 1];
            bi.StreamSource.Read(buffer, 0, (int)bi.StreamSource.Position - 1);
            return buffer;
        }
    }

Any ideas as to what I could do better?

Link to comment
Share on other sites

6 answers to this question

Recommended Posts

  • 0

what are you trying to show? If I were you, I would save the image, then load it directly as opposed to a stream.

Link to comment
Share on other sites

  • 0

The reason I'm not saving the images is because they are all stored in the databases as byte arrays and I don't want to use HD space.

That's fair, though a few kb's isn't that much. Glad you got it working, and is a good tip if I need to do this.

Link to comment
Share on other sites

  • 0

It's not the cause of the problem, but in general you should avoid calling Dispose() manually: that's what the using statement is for. Here:


using (MemoryStream mStream = new MemoryStream(buffer)) {
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = mStream;
bi.EndInit();
return bi;
}[/CODE]

It's not simply because it looks cleaner, it's mainly because you're guaranteed Dispose() will be called even if an exception causes the method to exit early.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.