c# BitmapImage保存为MemoryStream时AccessViolationException
本文关键字:AccessViolationException MemoryStream BitmapImage 保存 | 更新日期: 2023-09-27 18:14:55
我试图通过内存流保存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'
下面的代码,在Save命令中抛出错误:
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))
{ ...
所讨论的图像通常是1000px x 500,所以不是很大。你知道是什么引起的吗?或者我还能如何在不使用内存流(不降低性能)的情况下进行转换?
原来是croppedbitmap的原始源bitmapimage(未在上面的代码中显示)导致了这个问题。
这个位图是通过URI从磁盘加载的。我发现将BitmapCacheOption设置为Onload
而不是None
可以消除错误。我猜图像在转换时还没有完全加载。然而,它降低了大约三倍的性能,这是不幸的。