Documentation Buy Contact Blog
Blog

How to use zlib in a C++ project

10 October 2013

zlib is easy to use, and simple to add to your project, especially compared to libJpeg. It's also a prerequisite to adding libPng. Pretty much all you need to do is grab all the *.c and *.h files from the source bundle you can download from www.zlib.net and slap them into your project. You probably also want to hold onto the README file.

Like with libJpeg on windows, you'll also need to disable warnings for unsafe function warnings with the compiler flag "/wd4996".

Here's a cool example using zlib to compress and decompress, you can download the full example here here.

#include "zlib/zlib.h"
#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[])
{
	const unsigned char pData[] = { ... };
	unsigned long nDataSize = 100;

	printf("Initial size: %d\n", nDataSize);

	unsigned long nCompressedDataSize = nDataSize;
	unsigned char * pCompressedData = new unsigned char[nCompressedDataSize];
	
	int nResult = compress2(pCompressedData, &nCompressedDataSize, pData, nDataSize, 9);

	if (nResult == Z_OK)
	{
		printf("Compressed size: %d\n", nCompressedDataSize);

		unsigned char * pUncompressedData = new unsigned char[nDataSize];
		nResult = uncompress(pUncompressedData, &nDataSize, pCompressedData, nCompressedDataSize);
		if (nResult == Z_OK)
		{
			printf("Uncompressed size: %d\n", nDataSize);
			if (memcmp(pUncompressedData, pData, nDataSize) == 0)
				printf("Great Success\n");
		}
		delete [] pUncompressedData;
	}

	delete [] pCompressedData;

	return 0;
}