【问题标题】:Faster way to convert BitmapSource to BitmapImage将 BitmapSource 转换为 BitmapImage 的更快方法
【发布时间】:2014-07-21 11:06:07
【问题描述】:

我们有一些视频软件可以将BitmapSource 转换为BitmapImage,然后使用以下代码将其绘制到屏幕上。问题是在较慢的机器上,这个过程似乎有点慢,运行 MS 分析器发现这些位图操作(即ToBitmapImage 函数)是我们进行的前 4 个最昂贵的调用。有什么办法可以提高效率吗?

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

【问题讨论】:

  • 为什么需要进行这种转换?几乎没有任何情况会明确需要 BitmapImage。至少对于以 ImageSource 作为参数的 DrawingContext.DrawImage 来说不是。通过继承,BitmapSource 已经是 ImageSource。
  • 我可以直接从 BitmapSource 绘制到绘图上下文吗?
  • DrawingContext.DrawImage 将 ImageSource 作为参数。通过继承,BitmapSource 已经是 ImageSource。
  • 谢谢,请将此作为答案发布,以便我接受。这是您看到的遗留代码,我应该已经发现它,但无论如何谢谢

标签: wpf performance xaml bitmapimage bitmapsource


【解决方案1】:

根本不需要转换。将VideoImage 属性的类型更改为ImageSourceBitmapSource。现在你直接将它作为参数传递给DrawImage

this.VideoImage = bitmapsource;
drawingContext.DrawImage(this.VideoImage, new Rect(0, 0, imageWidth, imageHeight));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 2017-12-03
    相关资源
    最近更新 更多