1、System.Drawing.Bitmap 转换 System.Windows.Media.ImageSource (Bitmap => ImageSource)
#region Change Bitmap To ImageSource
[System.Runtime.InteropServices.DllImport("gdi32.dll", SetLastError = true)]
private static extern bool DeleteObject(IntPtr hObject);
public static System.Windows.Media.ImageSource ChangeBitmapToImageSource(System.Drawing.Bitmap bitmap)
{
IntPtr hBitmap = bitmap.GetHbitmap();
System.Windows.Media.ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
System.Windows.Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
if (!DeleteObject(hBitmap))//注意内存的释放,否则内容持续增大,导致内存不足
{
throw new System.ComponentModel.Win32Exception();
}
return wpfBitmap;
}
#endregion
2、String path => ImageSource
private static object lockObj = new object();
public static ImageSource BitmapFromFileWithCache(String source)
{
var bitmap = new BitmapImage();
try
{
if (System.IO.File.Exists(source))
{
using (Stream stream = System.IO.File.OpenRead(source))
{
if (stream != null)
{
lock (lockObj)
{
bitmap.BeginInit();
bitmap.StreamSource = stream;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
stream.Dispose();//释放占用的资源
}
}
}
}
}
catch (Exception ex)
{
}
return bitmap;
}
3、Uri => ImageSource
private static object lockObj = new object();
public static ImageSource BitmapFromUri(Uri source)
{
var bitmap = new BitmapImage();
try
{
var temp = new BitmapImage(source);
temp = null;
lock (lockObj)
{
bitmap.BeginInit();
bitmap.UriSource = source;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
}
}
catch { }
return bitmap;
}
4、Stream => ImageSource
private static object lockObj = new object();
public static ImageSource BitmapFromFileWithCache(Stream stream)
{
var bitmap = new BitmapImage();
try
{
if (stream != null)
{
lock (lockObj)
{
bitmap.BeginInit();
bitmap.StreamSource = stream;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
stream.Dispose();//释放占用的资源
}
}
}
catch (Exception ex)
{
}
return bitmap;
}