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;
}
}
上一篇:4.3 Reduction代码(Heterogeneous Parallel Programming class lab)


下一篇:java语言中数值自动转换的优先顺序