Bitmap转换成BitmapImage
1 public BitmapImage BitmapToBitmapImage(System.Drawing.Bitmap bitmap) 2 { 3 MemoryStream ms = new MemoryStream(); 4 bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png); 5 BitmapImage bit3 = new BitmapImage(); 6 bit3.BeginInit(); 7 bit3.StreamSource = ms; 8 bit3.EndInit(); 9 return bit3; 10 }
skin是资源文件中的文件名,类型为png。
不知道效率怎么样。
看了下面的文章,感觉效率不怎么样,想寻找一种好一点的方法:
http://blog.csdn.net/yxlnmj/article/details/5801842
附:从资源文件中读取图片到WPF中的方法
//方法一 //Bitmap bitmap = (Bitmap)Properties.Resources.skin; //方法二 //Bitmap bitmap2 = (Bitmap)Properties.Resources.ResourceManager.GetObject("skin"); // BitmapImage image = BitmapToBitmapImage(bitmap); //this.image.Source = image;
除了上述方法以外,还有一种方法可以将Bitmap转换为BitmapSource,而BitmapSource是继承自BitmapImage的。
之所以要调DeleteObject这个API函数,是因为不释放这个句柄会引起内存泄露
 1         [System.Runtime.InteropServices.DllImport("gdi32.dll")]
 2         public static extern bool DeleteObject(IntPtr hObject);
 3 
 4        
 5 
 6         public BitmapSource BitmapToBitmapSource(System.Drawing.Bitmap bitmap)
 7         {
 8             IntPtr hBitmap = bitmap.GetHbitmap();
 9 
10             try
11             {
12                 var source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
13                 
14             }
15             finally
16             {
17                 DeleteObject(hBitmap);
18             }
19         }    
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号