如何在C#内存中使用JPEG或PNG压缩图像?

时间:2017-02-08 20:32:48

标签: c# stream compression jpeg emgucv

我目前正在使用C#和EmguCV(OpenCV),并希望使用当前由Mat类表示的JPEG / PNG压缩/解压缩图像。我不想将它存储在磁盘上,只需将其压缩在内存中即可。目标是稍后通过TCP / IP传输它。

以下任务的某些代码段非常受欢迎:

A. Compress:   Mat -> JPEG/PNG compressed byte[]
B. Decompress: JPEG/PNG compressed byte[] -> Mat

1 个答案:

答案 0 :(得分:0)

这是压缩Mat对象的最终代码,JPG返回一个字节数组进行网络传输:

    using Emgu.CV;
    using System.Drawing.Imaging;

    private VideoQuality quality;
    private ImageCodecInfo codecInfo;
    private EncoderParameters encoderParameters;

    public byte[] compress(Mat image) {
        using(MemoryStream memstream = new MemoryStream()) {
            long tstart = Toolkit.CurrentTimeMillis();
            image.Bitmap.Save(memstream, codecInfo, encoderParameters);
            return memstream.ToArray();
        }
    }

    private void setVideoQuality(long quality) {
        this.codecInfo = getEncoder(ImageFormat.Jpeg);
        this.encoderParameters = new EncoderParameters(1);
        encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);
    }

    private ImageCodecInfo getEncoder(ImageFormat format) {
        ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
        foreach(ImageCodecInfo codec in codecs) {
            if(codec.FormatID == format.Guid) {
                return codec;
            }
        }
        return null;
    }

这是解码字节数组的相应代码:

    private Image createImage(byte[] bytes) {
        using (MemoryStream memstream = new MemoryStream(bytes, 0, bytes.Length)) {
            memstream.Position = 0;
            return Image.FromStream(memstream, true);
        }
    }

希望这有助于某人:-)感谢您的帮助!