WPF的等效功能是什么?

时间:2014-03-27 16:16:22

标签: c# wpf image bitmap

我有以下在Windows窗体中运行的功能,但我需要帮助才能使它在带有图像控件的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;
    }

任何帮助将不胜感激。 感谢

1 个答案:

答案 0 :(得分: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可能会有所帮助。

相关问题