【问题标题】:What is the equivalent function for WPF?WPF 的等效功能是什么?
【发布时间】:2014-03-27 16:16:22
【问题描述】:

我有以下在 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;
    }

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

【问题讨论】:

  • 那么到底是什么不起作用?
  • 考虑使用WriteableBitmap
  • PixelFormat.Format24bppRgb 在 WPF 中无法识别
  • 你引用的是 System.Drawing dll 吗?

标签: c# wpf image bitmap


【解决方案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;

image 是一个Image 控件。

另外,请查看this question,因为它提到了一些关于bmp.GetHbitmap() 泄漏句柄的重要事实。

最后,这个article 可能会有所帮助。

【讨论】:

    猜你喜欢
    • 2019-02-03
    • 1970-01-01
    • 2012-10-16
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多