How to compress Image in gzip format

Some times the Size of images are too large and in some of the applications images are needed to save on particular server but because off large size it takes lots off time to save into server.If we compress that image into a particular format then we can save some space of server.

Step 1 – Create one Category and add libz.dylib library.

Step 2 – in .h file i.e in interface file mention the list of methods.

here the name of category is GZIP.

@interface NSData (GZIP)

and mention the list of methods.

– (NSData *)gzippedDataWithCompressionLevel:(float)level;

– (NSData *)gzippedData;

and end the interface using


Step 3 – in .m file i.e in implementation file

#import <zlib.h>

#define CHUNK_SIZE 16384

add the implementation of listed methods.

@implementation NSData (GZIP)

– (NSData *)gzippedDataWithCompressionLevel:(float)level{

if ([self length]){

z_stream stream;

stream.zalloc = Z_NULL;

stream.zfree = Z_NULL;

stream.opaque = Z_NULL;

stream.avail_in = (uint)[self length];

stream.next_in = (Bytef *)[self bytes];

stream.total_out = 0;

stream.avail_out = 0;

int compression = (level < 0.0f)? Z_DEFAULT_COMPRESSION: (int)roundf(level * 9);

if (deflateInit2(&stream, compression, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) == Z_OK){

NSMutableData *data = [NSMutableData dataWithLength:CHUNK_SIZE];

while (stream.avail_out == 0){

if (stream.total_out >= [data length]){

data.length += CHUNK_SIZE;


stream.next_out = [data mutableBytes] + stream.total_out;

stream.avail_out = (uint)([data length] – stream.total_out);

deflate(&stream, Z_FINISH);



data.length = stream.total_out;

return data;



return nil;


– (NSData *)gzippedData{

return [self gzippedDataWithCompressionLevel:-1.0f];



Step 4 – import category where we want to compress image

#import “NSData+GZIP.h”

Step 5 – Convert image into NSData

NSData *userFile = UIImageJPEGRepresentation(img, 1.0f);

Step 6 – call the gzippedData method.

NSData *compressedData = [userFile gzippedData];

Now Compressed image is in compressedData variable.


Thank You.

Need more help?

Hi there, was your problem or query resolved? If not & need more assistance, please do reach out to us at, we'll be more than delighted to help. Nanostuffs has 7+ years of extensive Salesforce & iOS/Android experience.
Holler Box