2011-11-14 47 views
1

我目前在將System.Drawing.Bitmap集成到WPF WriteableBitmap中時出現了一些問題。將System.Drawing.Bitmap複製到WriteableBitmap的區域

我想從Bitmap複製到WriteableBitmap的位置(X,Y)。

以下代碼顯示了我如何試圖做到這一點。

BitmapData Data = Bitmap.LockBits(new Rectangle(0, 0, Bitmap.Width, Bitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); 
WriteableBitmap.Lock(); 

//CopyMemory(WriteableBitmap.BackBuffer, Data.Scan0, ImageBufferSize); 

Int32Rect Rect = new Int32Rect(X, Y, Bitmap.Width, Bitmap.Height); 
WriteableBitmap.AddDirtyRect(Rect); 
Bitmap.UnlockBits(Data); 
Bitmap.Dispose();` 

非常感謝,

Neokript

回答

3

使用WritableBitmap.WritePixels。這將防止使用非託管代碼。

BitmapData Data = Bitmap.LockBits(new Rectangle(0, 0, Bitmap.Width, Bitmap.Height), 
    ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); 

try 
{  
    WritableBitmap.WritePixels(
     new Int32Rect(0,0,Bitmap.Width, Bitmap.Height), 
     Data.Scan0, 
     Data.Stride, 
     X, Y); 
} 
finally 
{ 
    Bitmap.UnlockBits(Data); 
} 

Bitmap.Dispose(); 
1

你應該同時鎖定BitmapDataWriteableBitmap。如果要將圖像繪製到特定的(x,y)位置,則還應該管理圖像的剩餘寬度和高度以進行繪製。

[DllImport("kernel32.dll",EntryPoint ="RtlMoveMemory")] 
public static extern void CopyMemory(IntPtr dest, IntPtr source,int Length); 

public void DrawImage(Bitmap bitmap) 
{ 
    BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); 

    try 
    { 
     writeableBitmap.Lock(); 
     CopyMemory(writeableBitmap.BackBuffer, data.Scan0, 
      (writeableBitmap.BackBufferStride * bitmap.Height)); 
     writeableBitmap.AddDirtyRect(new Int32Rect(0, 0, bitmap.Width, bitmap.Height)); 
     writeableBitmap.Unlock(); 
    } 
    finally 
    { 
     bitmap.UnlockBits(data); 
     bitmap.Dispose(); 
    } 
} 

並在代碼:

Bitmap bitmap = new Bitmap("pic.jpg"); // obtain it from anywhere, memory, file, stream ,... 

writeableBitmap = new WriteableBitmap(
         bitmap.Width, 
         bitmap.Height, 
         96, 
         96, 
         PixelFormats.Pbgra32, 
         null); 

imageBox.Source = writeableBitmap; 

DrawImage(bitmap); 

我已成功地渲染使用這種方法29 fps的1080P的短片。

相關問題