如何在 C# WPF 中将 byte[] 转换为 BitmapSource

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

我有一个图像的字节缓冲区 (byte[])。我必须将 byte[] 转换为 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);
                }
            }

如何将 byte[] 转换为 BitmapSource 以调用上面指定的函数。

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

   }