-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
Compressor.cs
53 lines (49 loc) · 1.75 KB
/
Compressor.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Threading.Tasks;
namespace Smidge.CompositeFiles
{
/// <summary>
/// Performs byte compression
/// </summary>
public static class Compressor
{
public static async Task<Stream> CompressAsync(CompressionType type, Stream original)
{
using (var ms = new MemoryStream())
{
Stream compressedStream = null;
if (type == CompressionType.Deflate)
{
compressedStream = new DeflateStream(ms, CompressionLevel.Optimal);
}
else if (type == CompressionType.GZip)
{
compressedStream = new GZipStream(ms, CompressionLevel.Optimal);
}
else if (type == CompressionType.Brotli)
{
compressedStream = new BrotliStream(ms, CompressionLevel.Optimal);
}
if (type != CompressionType.None)
{
using (compressedStream)
{
await original.CopyToAsync(compressedStream);
}
}
else
{
await original.CopyToAsync(ms);
}
//NOTE: If we just try to return the ms instance, it will simply not work
// a new stream needs to be returned that contains the compressed bytes.
// I've tried every combo and this appears to be the only thing that works.
//byte[] output = ms.ToArray();
return new MemoryStream(ms.ToArray());
}
}
}
}