How to compress image byte[] array to JPEG/PNG and return ImageSource object

喜你入骨 提交于 2019-12-06 06:27:27

问题


I have an image (in the form of a byte[] array) and I want to get a compressed version of it. Either a PNG or JPEG compressed version.

I use the following code at the minute:

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);
}

How do I extend this so that I can compress and return the compressed version of image source (with the degraded quality).

Thanks in advance!


回答1:


Using the right encoder like PngBitMapEncoder should work:

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;
        }            
    }


来源:https://stackoverflow.com/questions/18609757/how-to-compress-image-byte-array-to-jpeg-png-and-return-imagesource-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!