Пример #1
0
    public static byte[] Deflate(ReadOnlySpan <int> ints)
    {
        if (ints == null)
        {
            throw new ArgumentNullException(nameof(ints));
        }
        byte[] input   = new byte[ints.Length * sizeof(int)];
        var    asBytes = MemoryMarshal.Cast <int, byte>(ints);

        asBytes.CopyTo(input.AsSpan());

        var deflater = new Deflater();

        deflater.SetLevel(Deflater.DEFAULT_COMPRESSION);
        deflater.SetInput(input);
        deflater.Finish();

        using var ms = new MemoryStream(input.Length);
        byte[] buf = new byte[1024];
        while (!deflater.IsFinished)
        {
            int count = deflater.Deflate(buf);
            ms.Write(buf, 0, count);
        }

        return(ms.ToArray());
    }
Пример #2
0
        /// <summary>
        /// Encode a RIF byte array to zRIF string.
        /// </summary>
        /// <param name="zrif">The zRIF string.</param>
        /// <returns>The zRIF string or null on error.</returns>
        public static string Encode(byte[] rif)
        {
            byte[] output = new byte[128 + 2];

            if ((rif.Length != 512) && (rif.Length != 1024))
            {
                Console.Error.WriteLine("[ERROR] invalid RIF length");
                return(null);
            }
            var deflater = new Deflater();

            deflater.SetDictionary(zrif_dict);
            deflater.SetInput(rif);
            deflater.SetLevel(Deflater.BEST_COMPRESSION);
            deflater.SetStrategy(DeflateStrategy.Default);
            deflater.Finish();
            int size = deflater.Deflate(output, 0, output.Length - 2);

            if (!deflater.IsFinished)
            {
                Console.Error.WriteLine("[ERROR] Deflate error");
                return(null);
            }
            // Don't have that much control over Window size so our header needs to be adjusted.
            if ((output[0] == 0x78) && (output[1] == 0xF9))
            {
                output[0] = 0x28;
                output[1] = 0xEE;
            }
            // Adjust the size to be a multiple of 3 so that we don't get padding
            return(Convert.ToBase64String(output, 0, ((size + 2) / 3) * 3));
        }
Пример #3
0
        private static MemoryStream Compress(MemoryStream stream)
        {
            stream.Position = 0;
            byte[]   input      = stream.ToArray();
            byte[]   size       = BitConverter.GetBytes(Convert.ToUInt32(input.Length));
            Deflater compressor = new Deflater();

            compressor.SetLevel(Deflater.BEST_SPEED);
            compressor.SetInput(input);
            compressor.Finish();
            MemoryStream bos = new MemoryStream(input.Length);

            byte[] buf = new byte[1024];
            while (!compressor.IsFinished)
            {
                int count = compressor.Deflate(buf);
                bos.Write(buf, 0, count);
            }
            MemoryStream result      = new MemoryStream();
            BinaryWriter writeBinary = new BinaryWriter(result);

            writeBinary.Write(size);
            writeBinary.Write(bos.ToArray());
            writeBinary.Close();
            return(result);
        }
Пример #4
0
        /// <summary>
        /// Compresses the specified byte range using the
        ///  specified compressionLevel (constants are defined in
        ///  java.util.zip.Deflater).
        /// </summary>
        public static byte[] Compress(sbyte[] value, int offset, int length, int compressionLevel)
        {
            /* Create an expandable byte array to hold the compressed data.
             * You cannot use an array that's the same size as the orginal because
             * there is no guarantee that the compressed data will be smaller than
             * the uncompressed data. */
            ByteArrayOutputStream bos = new ByteArrayOutputStream(length);

            Deflater compressor = SharpZipLib.CreateDeflater();

            try
            {
                compressor.SetLevel(compressionLevel);
                compressor.SetInput((byte[])(Array)value, offset, length);
                compressor.Finish();

                // Compress the data
                var buf = new byte[1024];
                while (!compressor.IsFinished)
                {
                    int count = compressor.Deflate(buf);
                    bos.Write(buf, 0, count);
                }
            }
            finally
            {
            }

            return(bos.ToArray());
        }
        public byte[] Compress(byte[] input, int offset, int length)
        {
            // Create the compressor with highest level of compression
            Deflater compressor = new Deflater();

            compressor.SetLevel(Deflater.BEST_COMPRESSION);

            // Give the compressor the data to compress
            compressor.SetInput(input, offset, length);
            compressor.Finish();

            /*
             * Create an expandable byte array to hold the compressed data.
             * You cannot use an array that's the same size as the orginal because
             * there is no guarantee that the compressed data will be smaller than
             * the uncompressed data.
             */
            MemoryStream bos = new MemoryStream(input.Length);

            // Compress the data
            byte[] buf = new byte[1024];
            while (!compressor.IsFinished)
            {
                int count = compressor.Deflate(buf);
                bos.Write(buf, 0, count);
            }

            // Get the compressed data
            return(bos.ToArray());
        }
Пример #6
0
 public void SetLevel(int level)
 {
     if (level < 1)
     {
         throw new ArgumentOutOfRangeException("level");
     }
     Deflater.SetLevel(level);
 }
Пример #7
0
        /// <summary>
        /// Sets the active compression level (0-9).  The new level will be activated
        /// immediately.
        /// </summary>
        /// <param name="level">The compression level to set.</param>
        /// <exception cref="ArgumentOutOfRangeException">
        /// Level specified is not supported.
        /// </exception>
        /// <see cref="Deflater"/>
        public void SetLevel(int level)
        {
            if (level < Deflater.NO_COMPRESSION || level > Deflater.BEST_COMPRESSION)
            {
                throw new ArgumentOutOfRangeException(nameof(level), "Compression level must be 0-9");
            }

            Deflater.SetLevel(level);
        }
Пример #8
0
        /////////////////////////////////////////////////////////////////////////////////////////
        /// Compression                                                                       ///
        /////////////////////////////////////////////////////////////////////////////////////////

        public static byte[] Compress(byte[] data, int compressionLevel)
        {
            Deflater defl = new Deflater();

            defl.SetInput(data);
            defl.SetLevel(compressionLevel);
            byte[] compressedData = new byte[100000];
            defl.Deflate(compressedData);

            return(compressedData);
        }
Пример #9
0
        /// <summary>
        ///   对data从offset开始,长度为len进行level级别压缩,输出到outs
        /// </summary>
        /// <param name="data"></param>
        /// <param name="offset"></param>
        /// <param name="length"></param>
        /// <param name="level"></param>
        /// <param name="outStream"></param>
        /// <returns></returns>
        public static void Compress(byte[] data, int offset, int length, int level, Stream outStream)
        {
            var deflater = new Deflater();

            if (level >= 0 && level <= 9)
            {
                deflater.SetLevel(level);
            }
            var deflaterOutputStream = new DeflaterOutputStream(outStream, deflater, 4 * 1024);

            deflaterOutputStream.Write(data, offset, length);
            deflaterOutputStream.Finish();
        }
Пример #10
0
        /// <summary>
        ///   对ins进行level级别压缩,输出到outs
        /// </summary>
        /// <param name="inStream"></param>
        /// <param name="level"></param>
        /// <param name="outStream"></param>
        /// <returns></returns>
        public static void Compress(Stream inStream, int level, Stream outStream)
        {
            var deflater = new Deflater();

            if (level >= 0 && level <= 9)
            {
                deflater.SetLevel(level);
            }
            var deflaterOutputStream = new DeflaterOutputStream(outStream, deflater, 4 * 1024);

            StdioUtil.CopyStream(inStream, deflaterOutputStream);
            deflaterOutputStream.Finish();
        }
Пример #11
0
        public static byte[] ZipBytes(byte[] input)
        {
            MemoryStream ms     = new MemoryStream();
            Deflater     zipper = new Deflater();

            zipper.SetLevel(5);
            Stream st = new DeflaterOutputStream(ms, zipper);

            st.Write(input, 0, input.Length);
            st.Flush();
            st.Close();
            byte[] result = (byte[])ms.ToArray();
            return(result);
        }
Пример #12
0
        public static byte[] Compress(byte[] content)
        {
            Deflater compressor = new Deflater();

            compressor.SetLevel(Deflater.BEST_COMPRESSION);

            compressor.SetInput(content);
            compressor.Finish();

            using (MemoryStream ms = new MemoryStream(content.Length))
            {
                byte[] buf = new byte[1024];
                while (!compressor.IsFinished)
                {
                    int n = compressor.Deflate(buf);
                    ms.Write(buf, 0, n);
                }
                return(ms.ToArray());
            }
        }
Пример #13
0
        public static byte[] Compress(byte[] content)
        {
            //return content;
            Deflater compressor = new Deflater();               //用于压缩数据包

            compressor.SetLevel(Deflater.BEST_COMPRESSION);

            compressor.SetInput(content);    // 要压缩的数据包
            compressor.Finish();             // 完成,

            using (MemoryStream bos = new MemoryStream(content.Length))
            {
                var buf = new byte[1024];
                while (!compressor.IsFinished)
                {
                    int n = compressor.Deflate(buf);                      // 压缩,返回的是数据包经过缩缩后的大小
                    bos.Write(buf, 0, n);
                }
                return(bos.ToArray());
            }
        }
Пример #14
0
        public static int Compress(byte[] input, byte[] buffer, ref byte[] result, int level = Deflater.BEST_COMPRESSION)
        {
            var deflater = new Deflater();

            deflater.SetLevel(level);
            deflater.SetInput(input);
            deflater.Finish();

            buffer = buffer ?? new byte[BuffSize];
            MemoryStream ms;

            if (result != null)
            {
                ms = new MemoryStream(result);
            }
            else
            {
                ms = new MemoryStream(input.Length);
            }

            var length = 0;

            while (!deflater.IsFinished)
            {
                var count = deflater.Deflate(buffer);
                ms.Write(buffer, 0, count);
                length += count;
            }

            if (result == null)
            {
                result = ms.ToArray();
            }
            ms.Dispose();

            return(length);
        }
Пример #15
0
        public override void Write(BinaryWriter NewPicture)
        {
            Deflater defl = new Deflater();

            defl.SetInput(decopressedData);
            defl.SetLevel(compression.FLEVEL);
            byte[] compressedData = new byte[100000];
            defl.Deflate(compressedData);
            //byte[] data = compressedData.Where(x => x != 0).ToArray();

            //byte[] compressedData = Compress(decopressedData);

            Console.WriteLine("{0} {1}", compressedData.Length, byteData.Length);

            /*foreach (byte b in compressedData) Console.Write(b);
             * Console.WriteLine("\n\n");
             * foreach (byte b in byteData) Console.Write(b);
             * Console.WriteLine("");*/

            NewPicture.Write(BitConverter.GetBytes(compressedData.Length));
            NewPicture.Write(byteSign);
            NewPicture.Write(compressedData);
            NewPicture.Write(byteCheckSum);
        }
Пример #16
0
    public static byte[] ZipBytes(byte[] input, int compressLevel)
    {
        UtilsFunc.Assert(input != null);
        Deflater compressor = new Deflater();

        compressor.SetLevel(compressLevel);

        compressor.SetInput(input);
        compressor.Finish();
        byte[] ret = null;

        using (MemoryStream bos = new MemoryStream(input.Length))
        {
            byte[] buf = new byte[1024];
            while (!compressor.IsFinished)
            {
                int count = compressor.Deflate(buf);
                bos.Write(buf, 0, count);
            }
            ret = bos.ToArray();
        }

        return(ret);
    }
    public static byte[] Compress(byte[] input)
    {
        if (input == null || input.Length == 0)
        {
            Debug.LogError("Compress error inputBytes Len = 0");
            return(input);
        }

        // Create the compressor with highest level of compression
        Deflater compressor = GetDeflater();

        compressor.SetLevel(Deflater.BEST_COMPRESSION);

        // Give the compressor the data to compress
        compressor.SetInput(input);
        compressor.Finish();

        /*
         * Create an expandable byte array to hold the compressed data.
         * You cannot use an array that's the same size as the orginal because
         * there is no guarantee that the compressed data will be smaller than
         * the uncompressed data.
         */
        MemoryStream result = new MemoryStream(input.Length);

        // Compress the data
        byte[] buffer = new byte[1024];
        while (!compressor.IsFinished)
        {
            int count = compressor.Deflate(buffer);
            result.Write(buffer, 0, count);
        }

        // Get the compressed data
        return(result.ToArray());
    }
Пример #18
0
 public void SetLevel(int level)
 {
     Deflater.SetLevel(level);
     _defaultCompressionLevel = level;
 }
Пример #19
0
        /// <summary>
        /// Starts a new Zip entry. It automatically closes the previous
        /// entry if present.
        /// All entry elements bar name are optional, but must be correct if present.
        /// If the compression method is stored and the output is not patchable
        /// the compression for that entry is automatically changed to deflate level 0
        /// </summary>
        /// <param name="entry">
        /// the entry.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// if entry passed is null.
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// if an I/O error occured.
        /// </exception>
        /// <exception cref="System.InvalidOperationException">
        /// if stream was finished
        /// </exception>
        /// <exception cref="ZipException">
        /// Too many entries in the Zip file<br/>
        /// Entry name is too long<br/>
        /// Finish has already been called<br/>
        /// </exception>
        public void PutNextEntry(ZipEntry entry)
        {
            if (entry == null)
            {
                throw new ArgumentNullException(nameof(entry));
            }

            if (entries == null)
            {
                throw new InvalidOperationException("ZipOutputStream was finished");
            }

            if (curEntry != null)
            {
                CloseEntry();
            }

            if (entries.Count == int.MaxValue)
            {
                throw new ZipException("Too many entries for Zip file");
            }

            CompressionMethod method = entry.CompressionMethod;
            int compressionLevel     = defaultCompressionLevel;

            // Clear flags that the library manages internally
            entry.Flags     &= (int)GeneralBitFlags.UnicodeText;
            patchEntryHeader = false;

            bool headerInfoAvailable;

            // No need to compress - definitely no data.
            if (entry.Size == 0)
            {
                entry.CompressedSize = entry.Size;
                entry.Crc            = 0;
                method = CompressionMethod.Stored;
                headerInfoAvailable = true;
            }
            else
            {
                headerInfoAvailable = (entry.Size >= 0) && entry.HasCrc && entry.CompressedSize >= 0;

                // Switch to deflation if storing isnt possible.
                if (method == CompressionMethod.Stored)
                {
                    if (!headerInfoAvailable)
                    {
                        if (!CanPatchEntries)
                        {
                            // Can't patch entries so storing is not possible.
                            method           = CompressionMethod.Deflated;
                            compressionLevel = 0;
                        }
                    }
                    else                       // entry.size must be > 0
                    {
                        entry.CompressedSize = entry.Size;
                        headerInfoAvailable  = entry.HasCrc;
                    }
                }
            }

            if (headerInfoAvailable == false)
            {
                if (CanPatchEntries == false)
                {
                    // Only way to record size and compressed size is to append a data descriptor
                    // after compressed data.

                    // Stored entries of this form have already been converted to deflating.
                    entry.Flags |= 8;
                }
                else
                {
                    patchEntryHeader = true;
                }
            }


            entry.Offset            = offset;
            entry.CompressionMethod = (CompressionMethod)method;

            curMethod    = method;
            sizePatchPos = -1;

            if ((useZip64_ == UseZip64.On) || ((entry.Size < 0) && (useZip64_ == UseZip64.Dynamic)))
            {
                entry.ForceZip64();
            }

            // Write the local file header
            WriteLeInt(ZipConstants.LocalHeaderSignature);

            WriteLeShort(entry.Version);
            WriteLeShort(entry.Flags);
            WriteLeShort((byte)entry.CompressionMethodForHeader);
            WriteLeInt((int)entry.DosTime);

            // TODO: Refactor header writing.  Its done in several places.
            if (headerInfoAvailable)
            {
                WriteLeInt((int)entry.Crc);
                if (entry.LocalHeaderRequiresZip64)
                {
                    WriteLeInt(-1);
                    WriteLeInt(-1);
                }
                else
                {
                    WriteLeInt(entry.IsCrypted ? (int)entry.CompressedSize + ZipConstants.CryptoHeaderSize : (int)entry.CompressedSize);
                    WriteLeInt((int)entry.Size);
                }
            }
            else
            {
                if (patchEntryHeader)
                {
                    crcPatchPos = BaseOutputStream.Position;
                }
                WriteLeInt(0);                  // Crc

                if (patchEntryHeader)
                {
                    sizePatchPos = BaseOutputStream.Position;
                }

                // For local header both sizes appear in Zip64 Extended Information
                if (entry.LocalHeaderRequiresZip64 || patchEntryHeader)
                {
                    WriteLeInt(-1);
                    WriteLeInt(-1);
                }
                else
                {
                    WriteLeInt(0);                      // Compressed size
                    WriteLeInt(0);                      // Uncompressed size
                }
            }

            byte[] name = ZipStrings.ConvertToArray(entry.Flags, entry.Name);

            if (name.Length > 0xFFFF)
            {
                throw new ZipException("Entry name too long.");
            }

            var ed = new ZipExtraData(entry.ExtraData);

            if (entry.LocalHeaderRequiresZip64)
            {
                ed.StartNewEntry();
                if (headerInfoAvailable)
                {
                    ed.AddLeLong(entry.Size);
                    ed.AddLeLong(entry.CompressedSize);
                }
                else
                {
                    ed.AddLeLong(-1);
                    ed.AddLeLong(-1);
                }
                ed.AddNewEntry(1);

                if (!ed.Find(1))
                {
                    throw new ZipException("Internal error cant find extra data");
                }

                if (patchEntryHeader)
                {
                    sizePatchPos = ed.CurrentReadIndex;
                }
            }
            else
            {
                ed.Delete(1);
            }

            if (entry.AESKeySize > 0)
            {
                AddExtraDataAES(entry, ed);
            }
            byte[] extra = ed.GetEntryData();

            WriteLeShort(name.Length);
            WriteLeShort(extra.Length);

            if (name.Length > 0)
            {
                BaseOutputStream.Write(name, 0, name.Length);
            }

            if (entry.LocalHeaderRequiresZip64 && patchEntryHeader)
            {
                sizePatchPos += BaseOutputStream.Position;
            }

            if (extra.Length > 0)
            {
                BaseOutputStream.Write(extra, 0, extra.Length);
            }

            offset += ZipConstants.LocalHeaderBaseSize + name.Length + extra.Length;
            // Fix offsetOfCentraldir for AES
            if (entry.AESKeySize > 0)
            {
                offset += entry.AESOverheadSize;
            }

            // Activate the entry.
            curEntry = entry;
            crc.Reset();
            if (method == CompressionMethod.Deflated)
            {
                Deflater.Reset();
                Deflater.SetLevel(compressionLevel);
            }
            size = 0;
        }
Пример #20
0
        public void PutNextEntry(ZipEntry entry)
        {
            bool hasCrc;

            if (entry == null)
            {
                throw new ArgumentNullException(nameof(entry));
            }
            if (_entries == null)
            {
                throw new InvalidOperationException("ZipOutputStream was finished");
            }
            if (_curEntry != null)
            {
                CloseEntry();
            }
            if (_entries.Count == 0x7fffffff)
            {
                throw new ZipException("Too many entries for Zip file");
            }
            CompressionMethod compressionMethod = entry.CompressionMethod;
            int compressionLevel = _defaultCompressionLevel;

            entry.Flags      &= 0x800;
            _patchEntryHeader = false;
            if (entry.Size == 0L)
            {
                entry.CompressedSize = entry.Size;
                entry.Crc            = 0L;
                compressionMethod    = CompressionMethod.Stored;
                hasCrc = true;
            }
            else
            {
                hasCrc = (entry.Size >= 0L) && entry.HasCrc;
                if (compressionMethod == CompressionMethod.Stored)
                {
                    if (!hasCrc)
                    {
                        if (!CanPatchEntries)
                        {
                            compressionMethod = CompressionMethod.Deflated;
                            compressionLevel  = 0;
                        }
                    }
                    else
                    {
                        entry.CompressedSize = entry.Size;
                        hasCrc = entry.HasCrc;
                    }
                }
            }
            if (!hasCrc)
            {
                if (!CanPatchEntries)
                {
                    entry.Flags |= 8;
                }
                else
                {
                    _patchEntryHeader = true;
                }
            }
            if (Password != null)
            {
                entry.IsCrypted = true;
                if (entry.Crc < 0L)
                {
                    entry.Flags |= 8;
                }
            }
            entry.Offset            = _offset;
            entry.CompressionMethod = compressionMethod;
            _curMethod    = compressionMethod;
            _sizePatchPos = -1L;
            if ((_useZip64 == UseZip64.On) || ((entry.Size < 0L) && (_useZip64 == UseZip64.Dynamic)))
            {
                entry.ForceZip64();
            }
            WriteLeInt(ZipConstants.LocalHeaderSignature);
            WriteLeShort(entry.Version);
            WriteLeShort(entry.Flags);
            WriteLeShort((byte)entry.CompressionMethodForHeader);
            WriteLeInt((int)entry.DosTime);
            if (hasCrc)
            {
                WriteLeInt((int)entry.Crc);
                if (entry.LocalHeaderRequiresZip64)
                {
                    WriteLeInt(-1);
                    WriteLeInt(-1);
                }
                else
                {
                    WriteLeInt(entry.IsCrypted ? (((int)entry.CompressedSize) + 12) : ((int)entry.CompressedSize));
                    WriteLeInt((int)entry.Size);
                }
            }
            else
            {
                if (_patchEntryHeader)
                {
                    _crcPatchPos = BaseOutputStream.Position;
                }
                WriteLeInt(0);
                if (_patchEntryHeader)
                {
                    _sizePatchPos = BaseOutputStream.Position;
                }
                if (entry.LocalHeaderRequiresZip64 || _patchEntryHeader)
                {
                    WriteLeInt(-1);
                    WriteLeInt(-1);
                }
                else
                {
                    WriteLeInt(0);
                    WriteLeInt(0);
                }
            }
            byte[] buffer = ZipConstants.ConvertToArray(entry.Flags, entry.Name);
            if (buffer.Length > 0xffff)
            {
                throw new ZipException("Entry name too long.");
            }
            ZipExtraData extraData = new ZipExtraData(entry.ExtraData);

            if (entry.LocalHeaderRequiresZip64)
            {
                extraData.StartNewEntry();
                if (hasCrc)
                {
                    extraData.AddLeLong(entry.Size);
                    extraData.AddLeLong(entry.CompressedSize);
                }
                else
                {
                    extraData.AddLeLong(-1L);
                    extraData.AddLeLong(-1L);
                }
                extraData.AddNewEntry(1);
                if (!extraData.Find(1))
                {
                    throw new ZipException("Internal error cant find extra data");
                }
                if (_patchEntryHeader)
                {
                    _sizePatchPos = extraData.CurrentReadIndex;
                }
            }
            else
            {
                extraData.Delete(1);
            }
            if (entry.AesKeySize > 0)
            {
                AddExtraDataAes(entry, extraData);
            }
            byte[] entryData = extraData.GetEntryData();
            WriteLeShort(buffer.Length);
            WriteLeShort(entryData.Length);
            if (buffer.Length > 0)
            {
                BaseOutputStream.Write(buffer, 0, buffer.Length);
            }
            if (entry.LocalHeaderRequiresZip64 && _patchEntryHeader)
            {
                _sizePatchPos += BaseOutputStream.Position;
            }
            if (entryData.Length > 0)
            {
                BaseOutputStream.Write(entryData, 0, entryData.Length);
            }
            _offset += (30 + buffer.Length) + entryData.Length;
            if (entry.AesKeySize > 0)
            {
                _offset += entry.AesOverheadSize;
            }
            _curEntry = entry;
            _crc.Reset();
            if (compressionMethod == CompressionMethod.Deflated)
            {
                Deflater.Reset();
                Deflater.SetLevel(compressionLevel);
            }
            _size = 0L;
            if (entry.IsCrypted)
            {
                if (entry.AesKeySize > 0)
                {
                    WriteAesHeader(entry);
                }
                else if (entry.Crc < 0L)
                {
                    WriteEncryptionHeader(entry.DosTime << 0x10);
                }
                else
                {
                    WriteEncryptionHeader(entry.Crc);
                }
            }
        }