[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)
{
//Bitmap bitmap = icon.ToBitmap();
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(this 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;
}
internal static class IconUtilities
{
// 这个是没有附加转换的,:)
public static ImageSource ToImageSource(this Icon icon)
{
ImageSource imageSource = Imaging.CreateBitmapSourceFromHIcon(
icon.Handle,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
return imageSource;
}
调用:ImageSource wpfBitmap = img.ToImageSource();
5.从ImageSource转换成Bitmap,是从ImageSource中取出UriSource.LocalPath,然后使用 new Bitmap(FileName)的方法获取。其他的方法我还没有找到,
// System.Windows.Controls.Image ImgUserHeadFaceCutEdit;
string str1 = ((BitmapImage)(ImgUserHeadFaceCutEdit.Source)).UriSource.AbsolutePath;// 此路径new Bitmap(str1)无法识别
string str2 = ((BitmapImage)(ImgUserHeadFaceCutEdit.Source)).UriSource.LocalPath ;
//Bitmap sourceImage = new Bitmap(sourceImageUri.ToString());
string str3 = strImgSourceFileName;
Console.WriteLine("AbsolutePath =" + str1);
Console.WriteLine("LocalPath =" + str2);
Console.WriteLine("srceFileName =" + str3);
这是运行结果:
AbsolutePath =C:/Documents%20and%20Settings/zp/%E6%A1%8C%E9%9D%A2/%E6%A1%8C%E9%9D%A2%E7%A7%80/10111411409225.jpg
LocalPath =C:\Documents and Settings\zp\桌面\桌面秀\10111411409225.jpg
srceFileName =C:\Documents and Settings\zp\桌面\桌面秀\10111411409225.jpg
谁找到了实现方法,留言下啊