2014-03-27 44 views
1

我有以下功能,在Windows窗體中工作,但我需要幫助,使其工作在WPF與圖像控制。什麼是WPF的等價函數?

public static Bitmap CreateBitmap(byte[] bytes, int width, int height) 
{ 
     var rgbBytes = new byte[bytes.Length * 3]; 
     for (var i = 0; i <= bytes.Length - 1; i++) 
     { 
      rgbBytes[(i * 3)] = bytes[i]; 
      rgbBytes[(i * 3) + 1] = bytes[i]; 
      rgbBytes[(i * 3) + 2] = bytes[i]; 
     } 
     var bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb); 

     var data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb); 

     for (var i = 0; i <= bmp.Height - 1; i++) 
     { 
      var p = new IntPtr(data.Scan0.ToInt32() + data.Stride * i); 
      System.Runtime.InteropServices.Marshal.Copy(rgbBytes, i * bmp.Width * 3, p, bmp.Width * 3); 
     } 

     bmp.UnlockBits(data); 

     return bmp; 
    } 

任何幫助將不勝感激。 感謝

+0

那究竟是不是工作? – nvoigt

+0

考慮使用[WriteableBitmap](http://msdn.microsoft.com/zh-cn/library/system.windows.media.imaging.writeablebitmap%28v=vs.110%29.aspx)。 –

+0

在WPF中無法識別PixelFormat.Format24bppRgb – Laskar78

回答

1

嘗試這樣:

BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
     bmp.GetHbitmap(), 
     IntPtr.Zero, 
     System.Windows.Int32Rect.Empty, 
     BitmapSizeOptions.FromWidthAndHeight(bmp.Width, bmp.Height)); 
image.Source = bs; 

imageImage控制。

另外,請檢查this question,因爲它提到了一些關於bmp.GetHbitmap()泄漏句柄的重要事實。

最後,這個article可能有幫助。

相關問題