将源设置为BitmapImage时出错

时间:2012-06-18 07:32:54

标签: c# windows-phone-7 memorystream bitmapimage

我是WP7开发人员。我使用以下功能:

public BitmapImage SetImageSource(byte[] byteArray)
{
    BitmapImage bitmap = new BitmapImage();          
    try
    {
        MemoryStream ms = new MemoryStream(byteArray, 0, byteArray.Length);
        bitmap.SetSource(ms);
        ms.Flush();
        ms.Dispose();
    }

    catch (Exception ex)
    {
       MessageBox.Show(ex.Message);
    }
    return bitmap;
}

将byteArray写入位图图像。 但在某些情况下,它会触发异常:

System.OutOfMemoryException was unhandled
Message=OutOfMemoryException
StackTrace:
       at MS.Internal.FrameworkCallbacks.NotifyManagedDebuggerOnNativeOOM()
       at MS.Internal.XcpImports.BitmapSource_SetSourceNative(IntPtr bitmapSource, CValue& byteStream)
       at MS.Internal.XcpImports.BitmapSource_SetSource(BitmapSource bitmapSource, CValue& byteStream)
       at System.Windows.Media.Imaging.BitmapSource.SetSourceInternal(Stream streamSource)
       at System.Windows.Media.Imaging.BitmapImage.SetSourceInternal(Stream streamSource)
       at System.Windows.Media.Imaging.BitmapSource.SetSource(Stream streamSource)
       at FileEncrypt.ListImage.SetImageSource(Byte[] byteArray)
       at FileEncrypt.ListImage.LoadFiles()
       at FileEncrypt.ListImage.ListImage_Loaded(Object sender, RoutedEventArgs e)
       at MS.Internal.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
       at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)

我使用try..catch block来捕获异常但未捕获异常。

1 个答案:

答案 0 :(得分:0)

我做了这个功能并且这样做

  private BitmapSource ConvertPic(Stream Image)
        {
            BitmapSource ContactImage;
            if (Image == null)
            {
                return ContactImage = null;
            }
            var bmp = new BitmapImage();
            bmp.SetSource(Image);
            ContactImage = bmp;
            return ContactImage;
        }