【问题标题】:C# Bitmap BitmapImage bitmapsourceC# 位图 BitmapImage 位图源
【发布时间】:2010-11-16 23:06:49
【问题描述】:

我在网上某处找到了一些代码。

unsafe static Bitmap SaveFrame(IntPtr pFrame, int width, int height)
    {
        try
        {
            int x, y;
            int linesize = width * 3;
            byte* scan0 = (byte*)Marshal.ReadIntPtr(pFrame);

            IntPtr bufferPtr = Marshal.AllocHGlobal(linesize * height);
            byte* buffer = (byte*)bufferPtr;

            for (y = 0; y < height; y++)
            {
                for (x = 0; x < linesize; x = x + 3)
                {
                    *buffer++ = (byte)*(scan0 + y * linesize + x + 2);
                    *buffer++ = (byte)*(scan0 + y * linesize + x + 1);
                    *buffer++ = (byte)*(scan0 + y * linesize + x);
                }
            }
            Bitmap b = new Bitmap(width, height, linesize, System.Drawing.Imaging.PixelFormat.Format24bppRgb, bufferPtr);



            return b;
        }
        catch (Exception ex) { throw new Exception(ex.Message); }
    }

上面的代码给了我一个有效的位图,但是我正在使用 WPF 并希望它在 BitmapImage 中

没有经过这个过程,我尝试了代码

byte[] ptr = ....
Marshal.Copy(pFrame, ptr , 0, ptr .Length);
BitmapImage aBitmapImage = new BitmapImage(); 
aBitmapImage.BeginInit();
aBitmapImage.StreamSource = new MemoryStream(ptr); //FLastImageMemStream;//
aBitmapImage.EndInit();

这不起作用...

我也试过

System.Windows.Media.Imaging.BitmapSource.Create(width, height, 96, 96,
    System.Windows.Media.PixelFormats.Rgb24, null, bufferPtr,linesize * height,
    width * 3 ));

它似乎也没有给我一个图像(在将它分配给 Image 的 Source 属性之后)

谁能给我任何提示? 谢谢 艾伦

【问题讨论】:

  • 它真的不清楚你想在这里实现什么。 将显示位图。这是你想做的吗?

标签: c# bitmap bitmapimage bitmapsource


【解决方案1】:

将数据直接加载到 BitmapImage 中不起作用,因为它需要图像文件格式的数据,就像您在 .bmp 或 .png 文件中看到的那样。您提供了原始像素数据。

您的第二种方法看起来应该可行,但有一些不必要的步骤。您找到的代码是将像素数据从 BGR24 重写为 RGB24,但您应该可以直接将其加载为 BGR24:

System.Windows.Media.Imaging.BitmapSource.Create(width, height, 96, 96,
    System.Windows.Media.PixelFormats.Bgr24, null, pFrame, linesize * height,
    width * 3 ));

无论如何,您是否详细说明了为什么它没有给您图像?创建位图时是否遇到任何异常?它是否给出了错误的颜色或错误的尺寸?你确定所有的源数据都在那里吗?创建 BitmapSource 后,您在其属性中看到了什么?

【讨论】:

    【解决方案2】:

    【讨论】:

    • 对不起,但出于性能原因,我试图绕过首先创建位图的部分,我只想将字节数组传递给 WPF BitmapImage 组件...我有一个字节数组,我从加密文件中接收到这些字节,我将其输入到我在网上找到的代码中,这可以工作......但是这段代码(它也是不安全的)正在使用位图组件。我正在尝试为 WPF 找到一种方法
    • 您是否尝试过在创建流后寻找到流的开头?
    猜你喜欢
    • 2014-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-18
    • 1970-01-01
    • 2015-08-23
    相关资源
    最近更新 更多