mercoledì 16 ottobre 2013

Convertire immagini Bitmap in ImageSource

Il seguente codice converte un immagine in formato Bitmap in formato ImageSource:



Code:
//Convert Bitmap to ImageSource
public ImageSource ToImageSource(System.DrawingBitmap source)
{
 BitmapSource bitSrc = null;

 var hBitmap = source.GetHbitmap();

 try
 {
  bitSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
   hBitmap,
   IntPtr.Zero,
   Int32Rect.Empty,
   BitmapSizeOptions.FromEmptyOptions());
 }
 catch
 {
  bitSrc = null;
 }
 finally
 {
  NativeMethods.DeleteObject(hBitmap);
 }

 return bitSrc;
}

//Class Utility
internal static class NativeMethods
{
 [DllImport("gdi32.dll")]
 [return: MarshalAs(UnmanagedType.Bool)]
 internal static extern bool DeleteObject(IntPtr hObject);
}

Cosa molto importante è la cancellazione dell'oggetto tramite la classe "NativeMethods" altrimenti potreste avere problemi di memoria.

Nessun commento:

Posta un commento