publicstaticstringBrEncoder(string str) { System.IO.Compression.BrotliEncoder encoder = new System.IO.Compression.BrotliEncoder(); var bytes = Encoding.Default.GetBytes(str); Span<byte> output = new Span<byte>(newbyte[bytes.Length * 2]); var res = encoder.Compress(bytes, output, outint consumed, outint written, true); byte[] resultArray = newbyte[written]; Array.Copy(output.ToArray(), resultArray, written); return Convert.ToBase64String(resultArray); } publicstaticstringBrDecoder(string EncodeB64Str) { var bytes = Convert.FromBase64String(EncodeB64Str); Span<byte> output = new Span<byte>(newbyte[4096]); System.IO.Compression.BrotliDecoder decoder = new System.IO.Compression.BrotliDecoder(); var res1 = decoder.Decompress(bytes, output, outint deconsumed, outint dewritten); var result = Encoding.Default.GetString(output); return result; }
publicstaticvoidTest1(string str) { var res1 = BrEncoder(str); Console.WriteLine(res1); var res2 = BrDecoder(res1); Console.WriteLine(res2); }
Brotli.NET
The .net implement of the brotli algorithm,provide similar interface to Google offical API.
Quality and window control is supported.
Supported and tested on:
Dotnet standard 2(.NET Framework [v4.6.1] and .net core [2] above)
Windows/Linux/MacOSX
.NET Framework v4.5
Besides quality controll,the library use the native runtime and its performance should be better than System.IO.Compress.BrotliStream.
Demo:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
using Brotli; publicstaticvoidTest3(string str) { var bytes = Encoding.Default.GetBytes(str); var output= bytes.CompressToBrotli(); string EncodeB64Str = Convert.ToBase64String(output); Console.WriteLine(EncodeB64Str);
var bytesNeedDecode = Convert.FromBase64String(EncodeB64Str); var decompressedData = bytesNeedDecode.DecompressFromBrotli(); var result = Encoding.Default.GetString(decompressedData); Console.WriteLine(result); }
using EasyCompressor; publicstaticvoidTest4(string str) { var _compressor = new BrotliCompressor(); var bytes = Encoding.Default.GetBytes(str); var compressedBytes = _compressor.Compress(bytes);
var bytesNeedDecode = Convert.FromBase64String(EncodeB64Str); var uncompressedBytes = _compressor.Decompress(bytesNeedDecode); var result = Encoding.Default.GetString(uncompressedBytes); Console.WriteLine(result); }
BrotliSharpLib
BrotliSharpLib 是 Google 提供的 brotli 库/压缩代码的完整 C# 端口。它旨在成为原始 C 代码的大部分 1:1 转换。截至参考实现的 v0.6.0,所有代码都是正确的。
这些项目使用最少的 API 集来确保与各种框架(包括 .NET Standard 和 .NET Core)兼容。它还支持 little-endian 和 big-endian 架构,并针对 x86、x64 和 ARM 处理器进行了优化。 (这个能在Blazor上使用)
var bytesNeedDecode = Convert.FromBase64String(EncodeB64Str); var uncompressedBytes = BrotliSharpLib.Brotli.DecompressBuffer(bytesNeedDecode,0,bytesNeedDecode.Length); var result = Encoding.Default.GetString(uncompressedBytes); Console.WriteLine(result); }