2009-06-04 6 views
2

BitmapDecoder을 사용하여 이미지를 저장하는 WPF 응용 프로그램을 개발했습니다. 이미지를 저장하는 중 나는wpf 응용 프로그램에서 BitmapDecoder 객체를 삭제하는 방법

작업 예외를 완료하는 데 필요한 메모리가 부족합니다.

코드는 다음과 같이 보입니다 :

BitmapDecoder imgDecoder = BitmapDecoder.Create(mem, 
BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.None); 

내가 BitmapDecoder 객체가 그 예외의 원인이 될 수있다 생각을; 객체를 어떻게 처리합니까?

+1

참고로, 귀하는 귀하의 질문에 대한 '동의'및/또는 upvote 정답으로 가정합니다. 이것이 바로 사람들이 StackOverflow에서 "고맙다"고 말하는 방식입니다. – ojrac

답변

1

BitmapDecoder는 일회용이 아닙니다. 더 이상 BitmapDecoder가 필요하지 않다면 BitmapDecoder에 대한 참조를 유지하지 말고 GC가 작업을 수행하고 필요할 때 사용하지 않는 메모리를 수집합니다.

+0

답장을 보내 주셔서 감사합니다. – ibrahimkhan

4

같은 문제가 발생했습니다. BitmapDecoder를 사용하여 수천 개의 이미지를로드하고 메모리 문제가 발생하는 앱이 있습니다. BitmapDecoder와의 모든 상호 작용을 처리하는 래퍼 클래스 ImageFileHandler를 만든 다음 WeakReference에 BitmapDecoder 인스턴스를 저장했습니다. 그래서 OS가 메모리를 필요로한다면, 약한 레퍼런스는 BitmapDecoder를 포기하고 ImageFileHandler가 필요할 때마다 필요하다면 새로운 이미지 파일을 생성 할 것입니다.

+0

나는 같은 문제를 겪고 있다고 생각한다. 당신의 솔루션에 대해 좀 더 설명해 주시겠습니까? – maxfridbe

2

BmpBitmapDecoder 있지만, 모든 디코더 (GifBitmapDecoder, PngBitmapDecoder, JpegBitmapDecoder, TiffBitmapDecoder)뿐만 아니라 그렇게 당신이 그들을 처분 할 수있는 모든

_myDecoder = null; 
GC.Collect(); 

말 그리고 가비지 컬렉터가 할 수 있도록하는 것입니다, 일회용 클래스 없습니다 그 직업.

BitmapDecoder의 풀을 만들고 이미지를 FileStream으로로드하고 이미지의 이진 데이터가 포함 된 이미지를로드 할 수 있습니다. 아래 코드는 당신에게 아이디어를 제공합니다 :

GC.Collect(); 
// Load the file stream if it hasn't been loaded yet 
if (_imageDataStream == null) 
    _imageDataStream = new FileStream(_imagePath, FileMode.Open, FileAccess.Read, FileShare.Read); 
else 
    _imageDataStream.Seek(0, SeekOrigin.Begin); 

string extension = System.IO.Path.GetExtension(_imagePath).ToUpper(); 
if (extension.Contains("GIF")) 
    _decoder = new GifBitmapDecoder(_imageDataStream, BitmapCreateOptions.PreservePixelFormat, 
     BitmapCacheOption.OnDemand); 
else if (extension.Contains("PNG")) 
    _decoder = new PngBitmapDecoder(_imageDataStream, BitmapCreateOptions.PreservePixelFormat, 
     BitmapCacheOption.OnDemand); 
else if (extension.Contains("JPG") || extension.Contains("JPEG")) 
    _decoder = new JpegBitmapDecoder(_imageDataStream, BitmapCreateOptions.PreservePixelFormat, 
     BitmapCacheOption.OnDemand); 
else if (extension.Contains("BMP")) 
    _decoder = new BmpBitmapDecoder(_imageDataStream, BitmapCreateOptions.PreservePixelFormat, 
     BitmapCacheOption.OnDemand); 
else if (extension.Contains("TIF")) 
    _decoder = new TiffBitmapDecoder(_imageDataStream, BitmapCreateOptions.PreservePixelFormat, 
     BitmapCacheOption.OnDemand); 
+0

"가비지 수집기가 그 일을하도록하십시오."- 따라서 GC를 수집하도록 강요하지 마십시오. 대부분의 경우 GC는 수행 할 작업을 알고 있습니다. "GC.Collect()"및 기타 gc 함수를 호출하면 성능 문제가 발생할 수 있습니다. – wischi

관련 문제