2012-07-05 6 views
4

이 코드를 사용하여 이미지를 바이너리 이미지로 변환합니다.메모리 스트림을 지우는 방법

public class ImageConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     var memStream = new MemoryStream(((MeetPoint_B2C.ServiceReference1.Binary)value).Bytes); 
     memStream.Seek(0, SeekOrigin.Begin); 
     var empImage = new BitmapImage(); 
     empImage.CreateOptions = BitmapCreateOptions.None; 
     empImage.SetSource(memStream); 
     return empImage; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

내 데이터베이스에서 20 개 이상의 이미지를로드하는 중 오류가 발생했습니다. 처리되지 않은 예외입니다. 요청이 지원되지 않습니다. 이미 메모리가 가득차 있다고 생각합니다. 그렇다면 메모리 스트림을 어떻게 재설정 할 수 있습니까? dispose() 또는 memorystream.setLength ~ 0을 사용할 수 있지만 코딩 방법은 무엇입니까? 당신이 필요가 없습니다 있지만 -

예외 세부

 
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 MeetPoint_B2C.ImageConverter.Convert(Object value, Type targetType, Object parameter, CultureInfo culture) 
     at System.Windows.Data.BindingExpression.ConvertToTarget(Object value) 
     at System.Windows.Data.BindingExpression.GetValue(DependencyObject d, DependencyProperty dp) 
     at System.Windows.DependencyObject.EvaluateExpression(DependencyProperty property, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry) 
     at System.Windows.DependencyObject.EvaluateBaseValue(DependencyProperty property, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, ValueOperation operation) 
     at System.Windows.DependencyObject.EvaluateEffectiveValue(DependencyProperty property, EffectiveValueEntry oldEntry, EffectiveValueEntry newEntry, ValueOperation operation) 
     at System.Windows.DependencyObject.UpdateEffectiveValue(DependencyProperty property, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, ValueOperation operation) 
     at System.Windows.DependencyObject.RefreshExpression(DependencyProperty dp) 
     at System.Windows.Data.BindingExpression.RefreshExpression() 
     at System.Windows.Data.BindingExpression.SendDataToTarget() 
     at System.Windows.Data.BindingExpression.SourceAcquired() 
     at System.Windows.Data.BindingExpression.System.Windows.IDataContextChangedListener.OnDataContextChanged(Object sender, DataContextChangedEventArgs e) 
     at System.Windows.Data.BindingExpression.DataContextChanged(Object sender, DataContextChangedEventArgs e) 
     at System.Windows.FrameworkElement.OnDataContextChanged(DataContextChangedEventArgs e) 
     at System.Windows.FrameworkElement.OnAncestorDataContextChanged(DataContextChangedEventArgs e) 
     at System.Windows.FrameworkElement.NotifyDataContextChanged(DataContextChangedEventArgs e) 
     at System.Windows.FrameworkElement.OnAncestorDataContextChanged(DataContextChangedEventArgs e) 
     at System.Windows.FrameworkElement.NotifyDataContextChanged(DataContextChangedEventArgs e) 
     at System.Windows.FrameworkElement.OnTreeParentUpdated(DependencyObject newParent, Boolean bIsNewParentAlive) 
     at System.Windows.DependencyObject.UpdateTreeParent(IManagedPeer oldParent, IManagedPeer newParent, Boolean bIsNewParentAlive, Boolean keepReferenceToParent) 
     at MS.Internal.FrameworkCallbacks.ManagedPeerTreeUpdate(IntPtr oldParentElement, IntPtr parentElement, IntPtr childElement, Byte bIsParentAlive, Byte bKeepReferenceToParent, Byte bCanCreateParent) 
     at MS.Internal.XcpImports.Measure_WithDesiredSizeNative(IntPtr element, Single inWidth, Single inHeight, Single& outWidth, Single& outHeight) 
     at MS.Internal.XcpImports.UIElement_Measure_WithDesiredSize(UIElement element, Size availableSize) 
     at System.Windows.UIElement.Measure_WithDesiredSize(Size availableSize) 
     at System.Windows.Controls.VirtualizingStackPanel.MeasureChild(UIElement child, Size layoutSlotSize) 
     at System.Windows.Controls.VirtualizingStackPanel.MeasureOverride(Size constraint) 
     at System.Windows.FrameworkElement.MeasureOverride(IntPtr nativeTarget, Double inWidth, Double inHeight, Double& outWidth, Double& outHeight) 
     at MS.Internal.XcpImports.MeasureOverrideNative(IntPtr element, Single inWidth, Single inHeight, Single& outWidth, Single& outHeight) 
     at MS.Internal.XcpImports.FrameworkElement_MeasureOverride(FrameworkElement element, Size availableSize) 
     at System.Windows.FrameworkElement.MeasureOverride(Size availableSize) 
     at System.Windows.FrameworkElement.MeasureOverride(IntPtr nativeTarget, Double inWidth, Double inHeight, Double& outWidth, Double& outHeight)

이 다음 .xaml

<Grid.Resources> 
    <src:ImageConverter x:Key="imgConverter"/> 
</Grid.Resources> 
<Image Grid.Column="1" Grid.Row="4" Height="136" HorizontalAlignment="Left" 
    Margin="16,16,0,0" Name="imgEmp" Stretch="Fill" 
    VerticalAlignment="Top" Width="200" 
    Source="{Binding Image, Converter={StaticResource imgConverter}}"/> 
+0

전화가 걸려 특정 이미지가 아니라고 확신 할 수 있습니까? –

+2

매번 다른 메모리 스트림을 사용하므로 아무 것도 재설정 할 필요가 없습니다. 예외는 뭔가 다른 것, 예외 처리기에서 변환 내부 코드를 래핑하고 정확한 예외를보고하려고합니다. –

+0

컨텍스트가 정확히 무엇인지 명확하지 않습니다. WCF * 서버 * 인 경우 WPF 클래스를 사용하는 것이 상대적으로 드뭅니다 ... –

답변

3

BitmapImage 객체가 스트림의 소유권을하기 때문에, 당신이 종료 할 수 없습니다 (또는 폐기) 적절하게, 그래서의 라인을 따라 뭔가 추천 : 호출 방법

public BitmapImage Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
{ 
    var empImage = new BitmapImage(); 
    empImage.CreateOptions = BitmapCreateOptions.None; 
    empImage.SetSource(new MemoryStream(((MeetPoint_B2C.ServiceReference1.Binary)value).Bytes);); 
    return empImage; 
} 

을 , 자신의 리소스 정리를 구현하십시오. BitmapImage는 IDisposable을 구현하지 않으므로 using 문을 사용할 수 없습니다. 마이크로 소프트는 명확하게 관리되지 않는 리소스에 대한 참조를 포함하는 경우는 IDisposable을 구현 고려해야합니다

public void ConvertBitmap() 
{ 
    BitmapImage img = null; 
    try 
    { 
     img = Convert(// pass in your params); 

     // do stuff with your img 
    } 
    finally 
    { 
     // dispose of the memorystream in case of exception 
     if(img != null && img.StreamSource != null) img.StreamSource.Dispose(); 
    } 
} 

이 원래 MemoryStream도 예외의 경우 제대로 정리되었는지 확인합니다.

2

당신은 이미 변환하도록 요청받을 새로운 MemoryStream 때마다 만드는 데 사용됩니다 이 경우 찾기. 아무 것도 재설정 할 필요가 없습니다.

당신은 정말 발생되는 것을 제외하고 정확히을 찾아야한다 - 메모리가 부족 인와는 아무것도하지 않을 수 있습니다. 스택 추적을 표시하도록 질문을 편집했지만 throw되는 예외의 유형은 표시하지 않았습니다. 한 가지 가능성은 WCF 서비스에서 WPF 컨트롤을 사용하는 것과 관련이 있다는 것입니다. 질문 태그가 아무 것도없는 경우입니다.

편집 : 당신은 MemoryStream 처분하지 않으려는 비록 당신이 그것을 완료하면, 당신은 당신이 BitmapImage 결과 처분 확인해야합니다. 불행히도 우리는 그 전선에 대한 조언을하기 위해 당신이하고있는 일에 대해 충분한 맥락을 가지고 있지 않습니다.

+0

하지만이 오류가 발생하여 많은 이미지를 변환 할 예정인 1 번 있습니다. –

+0

@ user1504015 : 죄송합니다. 귀하의 의견을 이해하지 못합니다. 다시 말해주십시오. –

+0

약 20 이미지를로드 할 때 코딩이 잘 실행되고 있지만 이미지가 20 이상일 때 위와 같은 오류가 발생합니다. –

관련 문제