WCF中Image.Source属性只支持ImageSource对象,不能把图片对象直接赋给Image.Source。可以采用以下办法,将Bitmap对象转换成ImageSource对象。
Bitmap bitmap ;
this.image1.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
但以上代码有一个需要注意的地方就是
bitmap.GetHbitmap()
Bitmap.GetHbitmap() 是创建一个GDI位图对象,因此该对象用完之后一定要手动释放,否则会造成内存GDI对象的残留。所以最正确的代码为:
IntPtr ptr = IntPtr.Zero;
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
private void SetImage(Bitmap bitmap)
{
IntPtr ptr = bitmap.GetHbitmap();
this.image1.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
ptr, IntPtr.Zero, Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
if (ptr != IntPtr.Zero)
{
DeleteObject(ptr);
}
}