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

Rob McCabe picture Rob McCabe · Sep 4, 2013 · Viewed 13.3k times · Source

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!

Answer

Chevul Ervin picture Chevul Ervin · Sep 4, 2013

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