Search code examples
javascriptnode.jsimagebase64compression

How to compress an image and encode as text?


the following use case is the basis for the question: Send an image as text through the wire? Doing it with the smallest size footprint.

I'm aware that to send binary data (the image) as text, the standard solution is to encode it to base64. However, as known, it increase the size by around 33%.

Is there a way to use compression and still send the image as text?

This answer answers it partially. Points that are still open:

If I encode to base64 and then gzip, for example, will the gz buffer be again binary or will it be string?

Or the other way around, can I first gzip the image in memory, and then encode to base64 to send it through the network?

Obs: an example code in node.js would be appreciated.

Thanks.


Solution

  • If you gzip Base-64 output, it is then binary again, with much of the Base-64 expansion undone. Though still a bit larger than the original. Compression will always produce binary output, so you must encode after compressing.

    If you want less than a 33% expansion, you can use more characters than 64. Find out how many different characters you can convey through your medium as "text" without corruption. It is likely a good bit more than 64. It might be in the range of 85 to 95. Call that n. Now you can encode with an expansion of approximately log(256) / log(n). You can then get the expansion down to 25% to 22%.