Search code examples
wpfbitmapbitmapsource

Is BitmapSource the only type can be used in Image Source?


We can use Bitmapsource object as the content of a Image control, However if I only have Bitmap object, can I use it directly, if I convert Bitmap to Bitmapsouce using the following method:

        Bitmap bitmap = imageObjToBeConvert;
        IntPtr HBitmap = bitmap.GetHbitmap();
        result = Imaging.CreateBitmapSourceFromHBitmap
            (HBitmap,
            IntPtr.Zero,
            Int32Rect.Empty,
            BitmapSizeOptions.FromEmptyOptions());
        DeleteObject(HBitmap);
        bitmap.Dispose();

It take some time. Is there any way to use Bitmap directly?

And I found BitmapSource seems can't be released directly, Is there a sample method to release the memory immediately, after the Bitmapsouce is not used again.


Solution

  • No, you cannot use Bitmap directly. This is because System.Drawing.Bitmap is a GDI+ bitmap, while classes like BitmapImage in System.Windows.Media.Imaging are D3D/DirectX.

    Regarding memory usage, you can't release it directly, but there is usually some sort of caching that goes in the background. There are ways that you can load a BitmapImage so that it ignores the cache.