1

I want do decompress images in JavaScript. I have compressed the images with C# using gzip. How do I decompress gzipped data in JavaScript?

C# code

public static byte[] Compress(byte[] raw)
{
    using (MemoryStream memory = new MemoryStream())
    {
        using (GZipStream gzip = new GZipStream(memory, CompressionMode.Compress, true))
        {
            gzip.Write(raw, 0, raw.Length);
        }
        return memory.ToArray();
    }
}
Kahbazi
  • 14,331
  • 3
  • 45
  • 76
  • There is no JS accessible builtin in browsers. You need to use a search engine of your choice to find a library. Is your question browser or node.js related? Btw.: Usually compression is the job of the webserver, so you won't need to compress explicitly. – Pinke Helga Apr 29 '17 at 06:47
  • See this duplicate and the original http://stackoverflow.com/q/14630238/495455 – Jeremy Thompson Apr 29 '17 at 06:55
  • What type of images are we talking about? Did you check wether they actually get compressed or wether they turn out bigger after the "compression"? Why do you think you need to compress these images "manually"? – Thomas Apr 29 '17 at 07:56
  • Does this answer your question? [Decompress gzip and zlib string in javascript](https://stackoverflow.com/questions/14620769/decompress-gzip-and-zlib-string-in-javascript) – Vladimir Panteleev Feb 10 '20 at 02:20

1 Answers1

2

First of all you have to close the GZipStream when you are done with it.

public static byte[] Compress(byte[] raw)
{
    using (MemoryStream memory = new MemoryStream())
    {
        using (GZipStream gzip = new GZipStream(memory, CompressionMode.Compress, true))
        {
            gzip.Write(raw, 0, raw.Length);
            gzip.Close();
        }
        return memory.ToArray();
    }
}

You can use pako for decompressing in javascript.

var base64Data = "COMPRESSED_BASE64_GZIP";
var compressData = atob(base64Data);
compressData = compressData.split('').map(function (e) {
    return e.charCodeAt(0);
});

var originalText = pako.ungzip(compressData, {to:"string"});
Kahbazi
  • 14,331
  • 3
  • 45
  • 76