WCF Image控件的Source属性的使用


       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);
            }
        }

 


 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值