我目前在将System.Drawing.Bitmap
集成到WPF 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
答案 0 :(得分: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 :(得分:1)
您应该锁定BitmapData
和WriteableBitmap
。如果要将图像绘制到特定的(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剪辑。