简体   繁体   中英

Cocoa Image Compression with NSImage

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM