Bitmap 与ImageSource之间的转换
作者:互联网
public class ImageConverter
{
[DllImport("gdi32.dll", SetLastError = true)]
private static extern bool DeleteObject(IntPtr hObject);
/// <summary>
/// 从bitmap转换成ImageSource
/// </summary>
/// <param name="icon"></param>
/// <returns></returns>
public static ImageSource ChangeBitmapToImageSource(Bitmap bitmap)
{
IntPtr hBitmap = bitmap.GetHbitmap();
ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
if (!DeleteObject(hBitmap))//记得要进行内存释放。否则会有内存不足的报错。
{
throw new System.ComponentModel.Win32Exception();
}
return wpfBitmap;
}
/// <summary>
/// 从Bitmap转换成BitmapSource
/// </summary>
/// <param name="bmp"></param>
/// <returns></returns>
public static BitmapSource ChangeBitmapToBitmapSource(Bitmap bmp)
{
BitmapSource returnSource;
try
{
returnSource = Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
}
catch
{
returnSource = null;
}
return returnSource;
}
/// <summary>
/// 从Icon到ImageSource的转换
/// </summary>
public ImageSource ChangeIconToImageSource(Icon icon)
{
ImageSource imageSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(
icon.Handle,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
return imageSource;
}
}
标签:IntPtr,转换,System,Bitmap,returnSource,ImageSource,public 来源: https://www.cnblogs.com/echohye/p/16368725.html