【问题标题】:c# BitmapImage AccessViolationException when saving as MemoryStreamc# BitmapImage AccessViolationException 保存为 MemoryStream 时
【发布时间】:2016-10-24 21:41:19
【问题描述】:

我正在尝试通过内存流保存 BitmapImage (System.Windows.Media.Imaging),以便将结果用于创建 Bitmap (System.Drawing)。

我在尝试将编码结果保存到内存流时间歇性地出错:

An exception of type 'System.AccessViolationException' occurred in PresentationCore.dll but was not handled in user code

Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

内存流的属性似乎表明发生了读取或写入超时。

WriteTimeout = 'msOut.WriteTimeout' threw an exception of type 'System.InvalidOperationException'

代码如下,保存命令时抛出错误:

         System.Windows.Media.Imaging.CroppedBitmap cbi = new System.Windows.Media.Imaging.CroppedBitmap(bi, new System.Windows.Int32Rect(
            (int)(imageViewBox[2] * imageViewBox[10]), (int)(imageViewBox[3] * imageViewBox[11]), 
            (int)((imageViewBox[4] - imageViewBox[2]) * imageViewBox[10]), (int)((imageViewBox[5] - imageViewBox[3]) * imageViewBox[11])));
        newImageSize = new Size(cbi.PixelWidth, cbi.PixelHeight);

        using (MemoryStream msOut = new MemoryStream())
        {
            System.Windows.Media.Imaging.BmpBitmapEncoder enc = new System.Windows.Media.Imaging.BmpBitmapEncoder();
            enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(cbi));
            // Throws access violation exception when zoomed on some images. Why?
            enc.Save(msOut);
            using (Bitmap temp = new Bitmap(msOut))
            { ...

有问题的图像通常为 1000 像素 x 500,因此不会很大。 有什么想法可能导致这种情况吗?或者任何想法我如何在不使用内存流的情况下进行转换(不降低性能?)

【问题讨论】:

    标签: c# bitmap system.drawing bitmapimage


    【解决方案1】:

    事实证明,裁剪位图的原始源位图图像(上述代码中未显示)导致了问题。

    此位图图像是通过 URI 从磁盘加载的。我发现将 BitmapCacheOption 设置为 Onload 而不是 None 可以消除错误。我猜图像在转换时没有完全加载。但是,它会降低大约三倍的性能,这很不幸。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-09
      • 1970-01-01
      • 2013-05-05
      • 2016-09-19
      • 2010-11-07
      • 1970-01-01
      相关资源
      最近更新 更多