[英]c# BitmapImage AccessViolationException when saving as MemoryStream
我正在尝试通过内存流保存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))
{ ...
有问题的图像通常为1000px x 500,因此不大。 任何想法可能是什么原因造成的? 或有任何想法,我又可以如何在不使用内存流的情况下进行转换(而不会降低性能?)
原来,cropedpedbitmap的原始源bitmapimage(上面的代码未显示)引起了问题。
该位图图像是通过URI从磁盘加载的。 我发现将BitmapCacheOption设置为Onload
而不是None
可以消除该错误。 我猜图像在转换时未完全加载。 但是,它将性能降低大约三倍,这是不幸的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.