如何将图像的byte[]数组压缩为JPEG/PNG并返回ImageSource对象

3
我有一张图片(以byte[]数组形式),我想获得一个压缩版本。可以是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);
}

如何扩展这个功能,以便可以压缩并返回图像源的压缩版本(质量降低)。

提前致谢!

1个回答

3
使用正确的编码器,比如 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;
        }            
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接