WPF等效于Bitmap.LockBits

时间:2011-05-10 13:59:44

标签: .net wpf winforms image image-processing

我在Win Forms应用程序中有以下工作代码:

Bitmap bitmap = new Bitmap(imageWidth, imageHeight, PixelFormat.Format32bppArgb);
Rectangle rect = new Rectangle(0, 0, imageWidth, imageHeight);
BitmapData bitmapData = bitmap.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);

Tao.DevIl.Il.ilConvertImage(Tao.DevIl.Il.IL_BGRA, Tao.DevIl.Il.IL_UNSIGNED_BYTE);
Tao.DevIl.Il.ilCopyPixels(0, 0, 0, imageWidth, imageHeight, 1, Tao.DevIl.Il.IL_BGRA, Tao.DevIl.Il.IL_UNSIGNED_BYTE, bitmapData.Scan0);

bitmap.UnlockBits(bitmapData);

我想将此代码转换为与WPF兼容并在UI中显示。这意味着我可能必须将System.Drawing.Bitmap转换为System.Windows.Media.Imaging.BitmapImage。

然而,我不知道在两者之间进行转换,而是想知道是否有更直接/更快的方法来做到这一点?就像在BitmapImage上执行类似LockBits()的操作一样。

ilCopyPixels()将IntPtr作为最后一个baram。在旧代码中我得到的形式是BitmapData.Scan0。

编辑:

感谢Erno的回答,我想出了以下内容:

WriteableBitmap bitmap = new WriteableBitmap(imageWidth, imageHeight, 96, 96, PixelFormats.Bgra32, null);
bitmap.Lock();
Tao.DevIl.Il.ilCopyPixels(0, 0, 0, imageWidth, imageHeight, 1, Tao.DevIl.Il.IL_BGRA, Tao.DevIl.Il.IL_UNSIGNED_BYTE, bitmap.BackBuffer);
bitmap.Unlock();

然而,当我将位图设置为图像的来源时,我什么都看不到。我没有得到任何例外。

谢谢!

2 个答案:

答案 0 :(得分:1)

看一下WriteableBitmap它会处理大部分细节。

答案 1 :(得分:0)

我当前的临时修复程序是使用以下代码将Bitmap转换为BitmapSource:

Bitmap bitmap = new Bitmap(imageWidth, imageHeight, PixelFormat.Format32bppArgb);
Rectangle rect = new Rectangle(0, 0, imageWidth, imageHeight);
BitmapData bitmapData = bitmap.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);

Tao.DevIl.Il.ilCopyPixels(0, 0, 0, imageWidth, imageHeight, 1, Tao.DevIl.Il.IL_BGRA, Tao.DevIl.Il.IL_UNSIGNED_BYTE, bitmapData.Scan0);
Tao.DevIl.Il.ilDeleteImages(1, ref imageId);

bitmap.UnlockBits(bitmapData);

using (MemoryStream str = new MemoryStream())
{
    bitmap.Save(str, ImageFormat.Bmp);
    str.Seek(0, SeekOrigin.Begin);
    BitmapDecoder bdc = new BmpBitmapDecoder(str, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
    // Retrieve the BitmapSource
    image1.Source = bdc.Frames[0];
}

显然,我宁愿直接创建一个BitmapSource,而不需要先创建一个Bitmap的额外开销。任何建议仍然欢迎!