Exemple #1
0
 /// <summary>
 /// use hight level compress data
 /// </summary>
 /// <param name="source"></param>
 /// <returns></returns>
 public static byte[] CompressHightLevel(ReadOnlySpan <byte> source)
 {
     using var outStream    = new MemoryStream();
     using var brotliStream = new System.IO.Compression.BrotliStream(outStream, System.IO.Compression.CompressionLevel.Optimal);
     brotliStream.Write(source);
     brotliStream.Close();
     return(outStream.ToArray());
 }
Exemple #2
0
 /// <summary>
 /// decompress data
 /// </summary>
 /// <param name="source"></param>
 /// <returns></returns>
 public static byte[] Decompress(ReadOnlySpan <byte> source)
 {
     using var inputStream = new MemoryStream();
     inputStream.Write(source);
     inputStream.Flush();
     inputStream.Position   = 0;
     using var outStream    = new MemoryStream();
     using var brotliStream = new System.IO.Compression.BrotliStream(inputStream, System.IO.Compression.CompressionMode.Decompress);
     brotliStream.CopyTo(outStream);
     return(outStream.ToArray());
 }
        public static Stream Decompress(Stream dataIn)
        {
#if UseBrotliLib
            MemoryStream decompressed = new MemoryStream();
            using (var decompressor = new BrotliSharpLib.BrotliStream(dataIn, System.IO.Compression.CompressionMode.Decompress))
                decompressor.CopyTo(decompressed);
            return(decompressed);
#elif NET48
            throw new NotSupportedException("The Brotli decompression is not supported in .Net 4.8");
#elif NETSTANDARD2_0
            throw new NotSupportedException("The Brotli decompression is not supported in .Net 4.8");
#else
            using (var decoder = new System.IO.Compression.BrotliStream(dataIn, System.IO.Compression.CompressionMode.Decompress))
            {
                var dataOut = new MemoryStream();
                decoder.CopyTo(dataOut);
                decoder.Flush();
                return(dataOut);
            }
#endif
        }
Exemple #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sfile"></param>
        /// <param name="targetfile"></param>
        private static void UnZipFile(string sfile, string targetfile)
        {
            try
            {
                Stopwatch sw = new Stopwatch();
                sw.Start();
                using (System.IO.Compression.BrotliStream bs = new System.IO.Compression.BrotliStream(System.IO.File.Open(sfile, System.IO.FileMode.Open), System.IO.Compression.CompressionMode.Decompress))
                {
                    using (var vss = System.IO.File.Open(targetfile, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite))
                    {
                        bs.CopyTo(vss);
                        vss.Flush();
                    }
                    bs.Close();
                }

                sw.Stop();
                LoggerService.Service.Info(" HisDataFileInfo4", "Zip 解压文件文件 " + targetfile + " 耗时:" + sw.ElapsedMilliseconds);
            }
            catch (Exception ex)
            {
                LoggerService.Service.Info(" HisDataFileInfo4", "Zip 解压文件文件 " + ex.Message);
            }
        }
Exemple #5
0
        private async static Task MeasureStringFor(FontDownload loader, string path)
        {
            byte[] data = null;

            data = await loader.LoadFrom(path);


#if UseOpenFont
            ZlibDecompressStreamFunc zipfunc = (byte[] dataIn, byte[] output) =>
            {
                using (var streamIn = new MemoryStream(dataIn))
                {
#if NET6_0
                    ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream input = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream(streamIn);

                    using (var streamOut = new MemoryStream(output))
                        input.CopyTo(streamOut);
#endif
                    return(true);
                }
            };
            WoffDefaultZlibDecompressFunc.DecompressHandler = zipfunc;

            BrotliDecompressStreamFunc brotlifunc = (byte[] dataIn, Stream dataOut) =>
            {
                using (var streamIn = new MemoryStream(dataIn))
                {
                    System.IO.Compression.BrotliStream deflate = new System.IO.Compression.BrotliStream(streamIn, System.IO.Compression.CompressionMode.Decompress);

                    deflate.CopyTo(dataOut);

                    return(true);
                }
            };
            Woff2DefaultBrotliDecompressFunc.DecompressHandler = brotlifunc;


            using (var ms = new System.IO.MemoryStream(data))
            {
                var reader  = new Typography.OpenFont.OpenFontReader();
                var preview = reader.ReadPreview(ms);

                Console.WriteLine("Loaded font reference " + preview.Name);
            }

            using (var ms = new System.IO.MemoryStream(data))
            {
                var    reader   = new Typography.OpenFont.OpenFontReader();
                var    full     = reader.Read(ms);
                string text     = "This is the text to measure";
                var    encoding = Scryber.OpenType.SubTables.CMapEncoding.WindowsUnicode;
                int    fitted;
                var    size = full.MeasureString(text, 0, 12, 10000, true, out fitted);


                Console.WriteLine("String Measured to " + size.ToString() + " and fitted " + fitted + " characters out of " + text.Length);
            }
#else
            TypefaceReader tfreader = new TypefaceReader();
            ITypefaceInfo  info;

            using (var ms = new System.IO.MemoryStream(data))
            {
                info = tfreader.ReadTypeface(ms, path);
                if (null == info)
                {
                    ExitClean("Could not read the info from the font file");
                    return;
                }
                else if (info.FontCount == 0)
                {
                    ExitClean("No fonts could be read from the data: " + info.ErrorMessage ?? "Unknown error");
                    return;
                }
                else
                {
                    Console.WriteLine("Read  " + info.FontCount + " typefaces from the font file " + info.Source);
                    foreach (var reference in info.Fonts)
                    {
                        Console.WriteLine("    " + reference.FamilyName + " (weight: " + reference.FontWeight.ToString() + ", width: " + reference.FontWidth + ", restrictions : " + reference.Restrictions + ", selections : " + reference.Selections.ToString() + ")");
                    }
                }
            }
            TypeMeasureOptions options = new TypeMeasureOptions();

            using (var ms = new System.IO.MemoryStream(data))
            {
                foreach (var fref in info.Fonts)
                {
                    Console.WriteLine();

                    ms.Position = 0;
                    var typeface = tfreader.GetFont(ms, info.Source, fref);

                    if (null == typeface || typeface.IsValid == false)
                    {
                        ExitClean("The font " + fref.ToString() + " was not valid");
                        return;
                    }
                    else
                    {
                        Console.WriteLine("Loaded font reference " + typeface.ToString());
                    }

                    var metrics = typeface.GetMetrics(options);

                    if (null != metrics)
                    {
                        var line = metrics.MeasureLine("This is the text to measure", 0, 12.0, 10000, options);
                        Console.WriteLine("Measured the string to " + line.RequiredWidth + ", " + line.RequiredHeight + " points, and fitted " + line.CharsFitted + " chars" + (line.OnWordBoudary ? " breaking on the word boundary." : "."));
                    }
                    else
                    {
                        ExitClean("No metrics were returned for the font " + typeface.ToString());
                        return;
                    }

                    var ttfData = typeface.GetFileData(DataFormat.TTF);
                    if (null == ttfData)
                    {
                        ExitClean("No data was returned in TTF format for the font " + typeface.ToString());
                    }
                    else
                    {
                        Console.WriteLine("TrueType font data was extracted at " + ttfData.Length + " bytes from the original data of " + data.Length);
                    }

                    var name = typeface.FamilyName;
                    if (typeface.FontWeight != WeightClass.Normal)
                    {
                        if (name.IndexOf(typeface.FontWeight.ToString()) < 0)
                        {
                            name += " " + typeface.FontWeight.ToString();
                        }
                    }
                    if ((typeface.Selections & FontSelection.Italic) > 0)
                    {
                        if (name.IndexOf("Italic") < 0)
                        {
                            name += " Italic";
                        }
                    }

                    loader.SaveToLocal("Output", name + ".ttf", ttfData);
                }
            }

#if Legacy
            var ttf = new Scryber.OpenType.TTFFile(data, 0);

            Console.WriteLine("Loaded font file " + ttf.ToString());

            var    encoding = Scryber.OpenType.SubTables.CMapEncoding.WindowsUnicode;
            string text     = "This is the text to measure";
            int    fitted;

            var size = ttf.MeasureString(encoding, text, 0, 12, 1000, true, out fitted);

            Console.WriteLine("String Measured to " + size.ToString() + " and fitted " + fitted + " characters out of " + text.Length);

            //Measure 90 wiout word boundary
            size = ttf.MeasureString(encoding, text, 0, 12, 90, false, out fitted);

            Console.WriteLine("String Measured to " + size.ToString() + " and fitted " + fitted + " characters out of " + text.Length + " to string '" + text.Substring(0, fitted) + "'");

            //Measure 90 with word boundary
            size = ttf.MeasureString(encoding, text, 0, 12, 90, true, out fitted);

            Console.WriteLine("String Measured to " + size.ToString() + " and fitted " + fitted + " characters out of " + text.Length + " to string '" + text.Substring(0, fitted) + "'");
#endif

#if Performance
            var stopWatch = System.Diagnostics.Stopwatch.StartNew();

            MeasureStringMeasurer(ttf);

            stopWatch.Stop();

            Console.WriteLine("To measure 4 different strings " + maxRepeat + " times took " + stopWatch.Elapsed.TotalMilliseconds + "ms");
#endif
#endif
        }
Exemple #6
0
        public async Task CompressionTest(BucketCompressionAlgorithm alg)
        {
            bool overshoot  = false;
            var  baseStream = new MemoryStream();

            for (int i = 0; i < 10; i++)
            {
                baseStream.Write(Guid.NewGuid().ToByteArray(), 0, 16);
            }

            for (int i = 0; i < 10; i++)
            {
                baseStream.Write(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }, 0, 8);
            }

            var baseData = baseStream.ToArray();

            Bucket compressed;

            switch (alg)
            {
            case BucketCompressionAlgorithm.ZLib:
#if !NET6_0_OR_GREATER
                compressed = baseData.AsBucket().Compress(alg);
#else
                {
                    var ms = new MemoryStream();
                    var zs = new System.IO.Compression.ZLibStream(ms, System.IO.Compression.CompressionLevel.Optimal);

                    zs.Write(baseData, 0, baseData.Length);
                    zs.Close();
                    compressed = ms.ToArray().AsBucket();
                }
#endif
                break;

            case BucketCompressionAlgorithm.GZip:
            {
                var ms = new MemoryStream();
                var zs = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionLevel.Optimal);

                zs.Write(baseData, 0, baseData.Length);
                zs.Close();
                compressed = ms.ToArray().AsBucket();
                break;
            }

            case BucketCompressionAlgorithm.Deflate:
            {
                var ms = new MemoryStream();
                var zs = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionLevel.Optimal);

                zs.Write(baseData, 0, baseData.Length);
                zs.Close();
                compressed = ms.ToArray().AsBucket();
                break;
            }

#if NET6_0_OR_GREATER
            case BucketCompressionAlgorithm.Brotli:
            {
                var ms = new MemoryStream();
                var zs = new System.IO.Compression.BrotliStream(ms, System.IO.Compression.CompressionLevel.Optimal);

                zs.Write(baseData, 0, baseData.Length);
                zs.Close();
                compressed = ms.ToArray().AsBucket();

                overshoot = true;
                break;
            }
#endif
            default:
                throw new InvalidOperationException();
            }

            var finishData     = overshoot ? Array.Empty <byte>() : Guid.NewGuid().ToByteArray();
            var compressedData = await compressed.Append(finishData.AsBucket()).ToArrayAsync();

            ushort firstTwo = NetBitConverter.ToUInt16(compressedData, 0);

            switch (alg)
            {
            case BucketCompressionAlgorithm.GZip:
                Assert.AreEqual(0x1F8B, firstTwo, $"Got 0x{firstTwo:x4}");
                break;

            case BucketCompressionAlgorithm.ZLib:
                bool isZlib = new ushort[] { 0x7801, 0x789C, 0x78da }.Contains(firstTwo);
                Assert.IsTrue(isZlib, $"Got 0x{firstTwo:x4}");
                break;

            case BucketCompressionAlgorithm.Deflate:
                // FirstTwo can be anything
                break;
            }


            var inner = compressedData.AsBucket();
            var bb    = await inner.Decompress(alg).ReadFullAsync(4096);

            Assert.AreEqual(baseData.Length, bb.Length);

            var decompressed = bb.ToArray();

            Assert.IsTrue(decompressed.SequenceEqual(baseData), "Same data after decompression");

            bb = await inner.ReadFullAsync(4096);

            Assert.AreEqual(finishData.Length, bb.Length);
            Assert.IsTrue(bb.ToArray().SequenceEqual(finishData));

            var r = await baseData.AsBucket().Compress(alg).ToArrayAsync();

            Stream rs;
            switch (alg)
            {
            case BucketCompressionAlgorithm.ZLib:
                rs = r.AsBucket().Decompress(BucketCompressionAlgorithm.ZLib).AsStream();
                break;

            case BucketCompressionAlgorithm.GZip:
                rs = new System.IO.Compression.GZipStream(new MemoryStream(r), System.IO.Compression.CompressionMode.Decompress);
                break;

            case BucketCompressionAlgorithm.Deflate:
                rs = new System.IO.Compression.DeflateStream(new MemoryStream(r), System.IO.Compression.CompressionMode.Decompress);
                break;

#if NET6_0_OR_GREATER
            case BucketCompressionAlgorithm.Brotli:
                rs = new System.IO.Compression.BrotliStream(new MemoryStream(r), System.IO.Compression.CompressionMode.Decompress);
                break;
#endif
            default:
                throw new InvalidOperationException();
            }

            byte[] resultBytes = new byte[4096];
            Assert.AreEqual(baseData.Length, rs.Read(resultBytes, 0, resultBytes.Length));
        }