문제

I have some code I found somewhere on the Net.

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); }
    }

This above code gives me a valid Bitmap, However I'm using WPF and want it to be in a BitmapImage

Without going through this process, Im trying the code

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

which does not work...

I have also tried

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

which also does not give me an image it seems (after assigning it to the Source property of Image)

Can anyone give me any hints? Thanks Allen

도움이 되었습니까?

해결책

Loading the data directly into the BitmapImage didn't work because it's expecting data in an image file format, like you'd see in a .bmp or .png file. You supplied raw pixel data instead.

Your second approach looks like it should work but has some unnecessary steps to it. The code you found is rewriting the pixel data from BGR24 to RGB24, but you should be able to just load it in directly as BGR24:

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

Anyway, do you have any details on why it's not giving you an image? Did you get any exceptions when creating the bitmap? Did it give the wrong colors or wrong size? Are you sure all the source data is there? What do you see on the properties of the BitmapSource after you create it?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top