Is BitmapSource the only type can be used in Image Source?
-
06-07-2019 - |
Question
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.
OTHER TIPS
- System.Windows.Media.Imaging..::.BitmapFrame
- System.Windows.Media.Imaging..::.BitmapImage
- System.Windows.Media.Imaging..::.CachedBitmap
- System.Windows.Media.Imaging..::.ColorConvertedBitmap
- System.Windows.Media.Imaging..::.CroppedBitmap
- System.Windows.Media.Imaging..::.FormatConvertedBitmap
- System.Windows.Media.Imaging..::.RenderTargetBitmap
- System.Windows.Media.Imaging..::.TransformedBitmap
- System.Windows.Media.Imaging..::.WriteableBitmap
All of these classes inherit from BitMapSource, so any of them could be used in that context.