所以我想利用Brotli,但我不熟悉
Python和C ..
我知道有人把它编译成Windows.exe.但是如何将它包装到DLL或.NET应用程序可以引用的东西?我知道有IronPython,我只是将所有的源文件导入IronPython项目,并编写一个调用到Brotli API并暴露它们的.NET适配器?但实际上,我甚至不确定Brotli API是Python还是C ..
看看tools / bro.cc,看起来像“entry”方法在encode.c和decode.c中定义为BrotliCompress(),BrotliDecompressBuffer(),BrotliDecompressStream()方法.所以我想可以从C类编译一个DLL.
解决方法
您可以使用提供完整流支持的Brotli.NET.
github:https://github.com/XieJJ99/brotli.net/.
Nuget:https://www.nuget.org/packages/Brotli.NET/.
将流压缩到brotli数据:
public Byte[] Encode(Byte[] input) { Byte[] output = null; using (System.IO.MemoryStream msInput = new System.IO.MemoryStream(input)) using (System.IO.MemoryStream msOutput = new System.IO.MemoryStream()) using (BrotliStream bs = new BrotliStream(msOutput,System.IO.Compression.CompressionMode.Compress)) { bs.SetQuality(11); bs.SetWindow(22); msInput.CopyTo(bs); bs.Close(); output = msOutput.ToArray(); return output; } }
解压缩一个brotli流:
public Byte[] Decode(Byte[] input) { using (System.IO.MemoryStream msInput = new System.IO.MemoryStream(input)) using (BrotliStream bs = new BrotliStream(msInput,System.IO.Compression.CompressionMode.Decompress)) using (System.IO.MemoryStream msOutput = new System.IO.MemoryStream()) { bs.CopyTo(msOutput); msOutput.Seek(0,System.IO.SeekOrigin.Begin); output = msOutput.ToArray(); return output; } }
要在Web应用程序中支持动态压缩,请在Global.asax.cs中添加如下代码:
protected void Application_PostAcquireRequestState(object sender,EventArgs e) { var app = Context.ApplicationInstance; String acceptEncodings = app.Request.Headers.Get("Accept-Encoding"); if (!String.IsNullOrEmpty(acceptEncodings)) { System.IO.Stream baseStream = app.Response.Filter; acceptEncodings = acceptEncodings.ToLower(); if (acceptEncodings.Contains("br") || acceptEncodings.Contains("brotli")) { app.Response.Filter = new Brotli.BrotliStream(baseStream,System.IO.Compression.CompressionMode.Compress); app.Response.AppendHeader("Content-Encoding","br"); } else if (acceptEncodings.Contains("deflate")) { app.Response.Filter = new System.IO.Compression.DeflateStream(baseStream,"deflate"); } else if (acceptEncodings.Contains("gzip")) { app.Response.Filter = new System.IO.Compression.GZipStream(baseStream,"gzip"); } } }