主要思路:先将Image转化为Bitmap,然后将Bitmap转化为BitmapSource或者是BitmapImage对象
1、写个静态方法,两种方法都可以
public class ImageWork
{
[DllImport("gdi32")]
static extern int DeleteObject(IntPtr o);
/// <summary>
/// Bitmap->BitmapSource
/// </summary>
/// <param name="bitmap"></param>
/// <returns></returns>
public static BitmapSource getBitMapSourceFromBitmap(Bitmap bitmap)
{
IntPtr intPtrl = bitmap.GetHbitmap();
BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(intPtrl,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
DeleteObject(intPtrl);
return bitmapSource;
}
/// <summary>
/// Bitmap --> BitmapImage
/// </summary>
/// <param name="bitmap"></param>
/// <returns></returns>
public static BitmapImage BitmapToBitmapImage(Bitmap bitmap)
{
using (MemoryStream stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Bmp);
stream.Position = 0;
BitmapImage result = new BitmapImage();
result.BeginInit();
result.CacheOption = BitmapCacheOption.OnLoad;
result.StreamSource = stream;
result.EndInit();
result.Freeze();
return result;
}
}
}
2、新建一个Bitmap对象,调用该方法。
processImage是一个System.Drawing.Image对象,我们将其转化为BitmapSource即可
Bitmap bmp = new Bitmap(processImage); // get bitmap
System.Windows.Media.Imaging.BitmapSource bmpResource = ImageWork.getBitMapSourceFromBitmap(bmp);
targetImg.Source = bmpResource;
或者
Bitmap bmp = new Bitmap(processImage); // get bitmap
BitmapImage bmpResource = ImageWork.BitmapToBitmapImage(bmp);
targetImg.Source = bmpResource;