Programming/C#, WPF

[WPF] Bitmap to Image Converter

영상털이범 2019. 5. 26. 03:14
반응형

 

Converter에서의 이미지 변환후 메모리 해제는 자동으로 이루어지지 않습니다.

꼭 GC.WaitForPendingFinalizers(); 를 호출하여 메모리 해제를 해줘야 합니다.

GC.Collect 만으로는 제대로 해제되지 않습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
[System.Runtime.InteropServices.DllImport("gdi32.dll")] 
private static extern bool DeleteObject(IntPtr hObject); 
 
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    if (value == null
        return null
 
    try 
    { 
        IntPtr hBitmap = ((System.Drawing.Bitmap)value).GetHbitmap(); 
 
        BitmapSource retval = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, 
            System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); 
 
        DeleteObject(hBitmap); 
        GC.Collect(System.GC.MaxGeneration, System.GCCollectionMode.Forced); 
        GC.WaitForPendingFinalizers();
 
        return retval; 
    } 
    catch (Exception ex) 
    { 
        Console.WriteLine(ex.ToString()); 
        return null
    }
}
cs
반응형