4

Possible Duplicate:
WPF Image to byte[]

Relative to this I have a BitmapSource image obtained by capturing image from webcam.How can i convert it to byte[] in C#

Community
  • 1
  • 1
Satheesh
  • 892
  • 2
  • 16
  • 38

2 Answers2

16

I got solution

        JpegBitmapEncoder encoder = new JpegBitmapEncoder();
        //encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
        encoder.QualityLevel = 100;          
       // byte[] bit = new byte[0];
        using (MemoryStream stream = new MemoryStream())
        {               
            encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
            encoder.Save(stream);
            byte[] bit = stream.ToArray(); 
            stream.Close();               
        }
Satheesh
  • 892
  • 2
  • 16
  • 38
  • 3
    You seem to be adding two bitmap frames. Any reason for that overhead? Also, why are you instantiating an empty byte array, only to overwrite it later? – Mathias Lykkegaard Lorenzen Aug 05 '15 at 05:52
  • @Mathias He's not adding two bitmap frames. He's creating a bitmap frame, adding it to the encoder's frames. He's then saving the encoder to the memory stream. He then converts the stream to a byte array. It is overhead, sure, but not any that can really be gotten around. Calling stream.Close(), though, is superfluous. The whole point of the 'using' block is to dispose of (which includes a .Close() call) the stream. – Meloviz May 25 '16 at 20:51
2

You can use the BitmapSource.CopyPixels method to copy the raw data out to a byte array. The stride parameter is the number of bytes in each image row. A 100-pixels wide RGBA image will have a stride of 100*4=400 bytes.

Check this SO discussion for the stride parameter and how it behaves for different image types

Community
  • 1
  • 1
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236