1

I have a bit of code that I have been working with to capture an image from a VideoCaptureElement from WPFMediaKit. it works great!

    bmp.Render(videoElement);
    BitmapEncoder encoder = new JpegBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(bmp));
    string now = DateTime.Now.Year + "" + DateTime.Now.Month + "" + DateTime.Now.Day + "" + DateTime.Now.Hour + "" + DateTime.Now.Minute + "" + DateTime.Now.Second;
    string filename = now + "pic.jpg";
    FileStream fstream = new FileStream(filename, FileMode.Open);
    encoder.Save(fstream);
    fstream.Close();

The problem I am facing though is that I need to get a byte[] data now rather than save a file. Currently I am doing this with a open filedialog box and a filestream:

            if (File.Exists(FileLocation))
            {
                //Retreave image from file and binary it to Object image
                using (FileStream stream = File.Open(FileLocation, FileMode.Open))
                {
                    BinaryReader br = new BinaryReader(stream);
                    byte[] data = br.ReadBytes(maxImageSize);
                    image = new Image(dlg.SafeFileName, data, fileSize);
                }
            }

What I'd like to do is to take the capture and rather than save a file, I'd like to get it as a byte[] type. Is there a way to convert either RenderTargetBitmap or BitmapEncoder to a byre[] array? Or possibly I'm thinking to convert those to a memory stream so a binary reader can use it?

thanks!

Herrozerro
  • 1,601
  • 1
  • 22
  • 37

2 Answers2

1

To convert an BitmapSource to a byte array you can do something like this, Where bmp is your BitmapSource or RenderTargetBitmap.

BitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmp));

byte[] arr = null;
using (MemoryStream memStream = new MemoryStream())
{
    encoder.Save(memStream);
    arr = stream.ToArray();
}
Zenchovey
  • 121
  • 7
0

In addition to the already mentioned saving to a stream in bmp format, you can also call CopyPixels on a BitmapSource.

That will give you the original pixels, in the original format, with no header.

See this msdn link