如何压缩图像byte []数组为JPEG / PNG和返回对象的ImageSource [英] How to compress image byte[] array to JPEG/PNG and return ImageSource object

查看:195
本文介绍了如何压缩图像byte []数组为JPEG / PNG和返回对象的ImageSource的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个形象(在一个byte []数组的形式),我想获得它的压缩版本。 。无论是PNG或JPEG压缩版本

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).

在此先感谢!

推荐答案

使用正确的编码器就像PngBitMapEncoder应该工作:

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

这篇关于如何压缩图像byte []数组为JPEG / PNG和返回对象的ImageSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆