How to Compress Files/Data Using Qt

File and data compression using Qt is extremely easy. There are many cases where you’d possibly like your data to be compressed (for example before sending it over network to a remote host) and in such cases you can use the approach below:

What I have described here shows both data and file compression.

Function qCompress is used to compress a QByteArray or any other raw data read from a file. Similarly you can also use qUncompress to un-compress your compressed files or data.

Note that compress_level parameter below specifies how much compression should be used. According to Qt Documentation valid values are between 0 and 9, with 9 corresponding to the greatest compression (i.e. smaller compressed data) at the cost of using a slower algorithm. Smaller values (8, 7, …, 1) provide successively less compression at slightly faster speeds. The value 0 corresponds to no compression at all. The default value is -1, which specifies zlib’s default compression.

And here is the code :

QFile fi("C:/Files/Input.jpg"); // this is your input file
QFile fo("C:/Files/output.compressed"); // this is your compressed output file

if ( &&
	int compress_level = 9; // compression level
	fo.write(qCompress(fi.readAll(), compress_level)); // read input, compress and write to output is a single line of code

Quite easy right? And here is how you can un-compress your compressed data:

QByteArray un_cmp = qUncompress(cmp);

cmp is the compressed data.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.