Copy a System.Drawing.Bitmap into a region of WriteableBitmap

感情迁移 提交于 2019-12-08 03:54:35

问题


I'm currently having some problems in integrating a System.Drawing.Bitmap into a WPF WriteableBitmap.

I want to copy from the Bitmap to position (X,Y) of the WriteableBitmap.

The following code shows how I've tried to do this.

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();`

Thanks a lot,

Neokript


回答1:


Use WritableBitmap.WritePixels. This will prevent using unmanaged code.

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



回答2:


You should lock both BitmapData and WriteableBitmap. If you want to draw the image to a specific (x,y) location, then you should also manage the remaining width and height of image for drawing.

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

And in your code:

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

I have managed to render a 1080P clip with 29 fps using this method.



来源:https://stackoverflow.com/questions/8127001/copy-a-system-drawing-bitmap-into-a-region-of-writeablebitmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!