0

We have some video software that converts BitmapSource into a BitmapImage which is then drawn to screen later using the following code. The problem is on slower machines this process seems to be a little slow, running the MS profiler it turns out that these Bitmap operations (namely the ToBitmapImage function) is in the top 4 most expensives calls we make. Is there anything I can do to improve the efficiency of this?

// Conversion
this.VideoImage = bitmapsource.ToBitmapImage();

// Drawing
drawingContext.DrawImage(this.VideoImage, new Rect(0, 0, imageWidth, imageHeight));

// Conversion code
internal static BitmapImage ToBitmapImage(this BitmapSource bitmapSource)
{
    JpegBitmapEncoder encoder = new JpegBitmapEncoder()
    MemoryStream memorystream = new MemoryStream();
    BitmapImage tmpImage = new BitmapImage();
    encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
    encoder.Save(memorystream);

    tmpImage.BeginInit();
    tmpImage.StreamSource = new MemoryStream(memorystream.ToArray());
    tmpImage.EndInit();

    memorystream.Close();
    return tmpImage;
}
Chris
  • 26,744
  • 48
  • 193
  • 345
  • Why do you need to do this conversion at all? There is hardly any situation where you would *explicitly* need a BitmapImage. At least not for DrawingContext.DrawImage, which takes an ImageSource as argument. A BitmapSource is already an ImageSource by inheritance. – Clemens Jul 21 '14 at 11:08
  • Can I draw directly from BitmapSource to a drawing context? – Chris Jul 21 '14 at 11:10
  • DrawingContext.DrawImage takes an ImageSource as argument. A BitmapSource is already an ImageSource by inheritance. – Clemens Jul 21 '14 at 11:12
  • Thankyou, please post this as an answer so I can accept.. This is legacy code you see, I should have spotted it really but thanks anyway – Chris Jul 21 '14 at 11:13

1 Answers1

3

The conversion isn't necessary at all. Change the type of your VideoImage property to ImageSource or BitmapSource. Now you directly pass it as parameter to DrawImage:

this.VideoImage = bitmapsource;
drawingContext.DrawImage(this.VideoImage, new Rect(0, 0, imageWidth, imageHeight));
Clemens
  • 123,504
  • 12
  • 155
  • 268