简体   繁体   中英

c# BitmapImage AccessViolationException when saving as MemoryStream

I'm trying to save a BitmapImage (System.Windows.Media.Imaging) via a memorystream so that the result can be used to create a Bitmap (System.Drawing).

I intermittently get an error when trying to save the encoded result to a memorystream:

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.

The properties of the memorystream seem to indicate that a read or write timeout has occurred.

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

Code below, the error is thrown at the Save command:

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

The images in question are generally 1000px x 500 so not massive. Any ideas what could be causing this? Or any ideas how else I could do the conversion without using a memorystream (without degrading performance?)

It turns out that the original source bitmapimage for the croppedbitmap (not shown in above code) was causing the issue.

This bitmapimage was loaded from disk via a URI. I've found that setting the BitmapCacheOption to Onload instead of None removes the error. I'm guessing the image was not fully loaded at the point of conversion. However, it reduces performance about threefold, which is unfortunate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM