c#BitmapImage保存为MemoryStream时的AccessViolationException

时间:2016-10-24 21:41:20

标签: c# bitmap system.drawing bitmapimage

我试图通过内存流保存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.

memorystream的属性似乎表明发生了读或写超时。

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))
            { ...

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

1 个答案:

答案 0 :(得分:0)

事实证明,croppedbitmap的原始源bitmapimage(上面代码中未显示)导致了这个问题。

这个bitmapimage是通过URI从磁盘加载的。我发现将BitmapCacheOption设置为#foo_spec.rb require 'selenium-webdriver' require 'rspec' describe "Contrived Example" do it "enters a search term" do driver = Selenium::WebDriver.for :firefox driver.navigate.to "http://google.com" element = driver.find_element(:name, 'q') element.send_keys "test string" sleep 1 expect(element['value']).to eq "test string" driver.quit end end 而不是Onload会删除错误。我猜测图像在转换点没有完全加载。然而,它将性能降低了三倍,这是不幸的。