Search code examples
c#wpfbitmapbitmapsource

How to convert byte[] to BitmapSource in c# WPF


I have a byte buffer (byte[]) of an image. I have to convert byte[] to BitmapSource (System.Windows.Media.Imaging.BitmapSource).

private void WriteAsJpeg(string fileName, BitmapSource bmp)
            {
                JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                BitmapFrame outputFrame = BitmapFrame.Create(bmp);
                encoder.Frames.Add(outputFrame);
                encoder.QualityLevel = 100;
                using (FileStream file = File.OpenWrite(fileName))
                {
                    encoder.Save(file);
                }
            }

How can i convert byte[] to BitmapSource in order to call the above specified function.


Solution

  • //array is a byte[]
     using (var memoryStream = new System.IO.MemoryStream(array))
        {
        var image = new BitmapImage();
        image.BeginInit();
        image.CacheOption = BitmapCacheOption.OnLoad; 
        image.StreamSource = memoryStream ;
        image.EndInit();
    
       }