Search code examples
wpfperformancexamlbitmapimagebitmapsource

Faster way to convert BitmapSource to BitmapImage


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;
}

Solution

  • 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));