I am writing a small Mac app to resize and compress jpeg files. So far I was able to resize the image properly. But I cannot compress the image (Reduce the image quality). My code is given below.
float tmph =width2* sourceSize.height/sourceSize.width;
NSSize outputSize = NSMakeSize(width2, tmph);
NSImage *anImage = [self scaleImage:sourceImage toSize:outputSize];
//compression
//NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:0.5] forKey:NSImageCompressionFactor];
NSData *imageDataOut = [anImage TIFFRepresentation];
NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:imageDataOut];
NSData *dataToWrite = [rep representationUsingType:NSPNGFileType properties:nil];
//NSData *dataToWrite = [rep representationUsingType:NSPNGFileType properties:options];
[dataToWrite writeToFile:outputPath atomically:NO];
scaleImage
is the function I use to resize the image. That works properly. In this code I have two lines commented. NSDictionary *options.....
line and NSData *dataToWrite....
lines are the two lines I added to get the compression. However with and without those two lines, I get the same size of files.
How can I get this working? Any advice?
You are setting the format type to NSPNGFileType. If you want to compress your image with JPEG, set it to NSJPEGFileType like the following.
NSData *imageDataOut = = [sourceImage TIFFRepresentation];
NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:imageDataOut];
NSDictionary *options = = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:0.5] forKey:NSImageCompressionFactor];
imageDataOut = [rep representationUsingType:NSJPEGFileType properties:options];
[imageDataOut writeToFile:exportpath atomically:YES];