Herrozerro
Herrozerro

Reputation: 1681

Capturing a byte[] image data from WPFMediaKit

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))
            {
                // Retrieve 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 byte[] array?

Or possibly I'm thinking to convert those to a memory stream so a binary reader can use it?

Thanks!

Upvotes: 1

Views: 1519

Answers (2)

user180326
user180326

Reputation:

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

Upvotes: 0

Zenchovey
Zenchovey

Reputation: 121

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

Upvotes: 1

Related Questions