Search code examples
c#wpfimagearraysimagesource

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


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!


Solution

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