C# 如何将图像字节[]数组压缩为JPEG/PNG并返回ImageSource对象

C# 如何将图像字节[]数组压缩为JPEG/PNG并返回ImageSource对象,c#,wpf,image,bytearray,imagesource,C#,Wpf,Image,Bytearray,Imagesource,我有一个图像(以字节[]数组的形式),我想得到它的压缩版本。PNG或JPEG压缩版本 我现在使用以下代码: private Media.ImageSource GetImage(byte[] imageData, System.Windows.Media.PixelFormat format, int width = 640, int height = 480) { return System.Windows.Media.Imaging.BitmapSource.Create(widt

我有一个图像(以字节[]数组的形式),我想得到它的压缩版本。PNG或JPEG压缩版本

我现在使用以下代码:

private Media.ImageSource GetImage(byte[] imageData, System.Windows.Media.PixelFormat format, int width = 640, int height = 480)
{

    return System.Windows.Media.Imaging.BitmapSource.Create(width, height, 96, 96, format, null, imageData, width * format.BitsPerPixel / 8);
}
如何扩展此功能,以便压缩并返回图像源的压缩版本(质量降低)


提前谢谢

使用正确的编码器,如PngBitMapEncoder,应该可以:

private ImageSource GetImage(byte[] imageData, System.Windows.Media.PixelFormat format, int width = 640, int height = 480)
    {
        using (MemoryStream memoryStream = new MemoryStream())
        {
            PngBitmapEncoder encoder = new PngBitmapEncoder();                                
            encoder.Interlace = PngInterlaceOption.On;
            encoder.Frames.Add(BitmapFrame.Create(BitmapSource.Create(width, height, 96, 96, format, null, imageData, width * format.BitsPerPixel / 8)));
            encoder.Save(memoryStream);
            BitmapImage imageSource = new BitmapImage();
            imageSource.BeginInit();
            imageSource.StreamSource = memoryStream;
            imageSource.EndInit();
            return imageSource;
        }            
    }