Objective c 基于NSImage的Cocoa图像压缩

Objective c 基于NSImage的Cocoa图像压缩,objective-c,image,macos,cocoa,image-compression,Objective C,Image,Macos,Cocoa,Image Compression,我正在编写一个小型Mac应用程序来调整和压缩jpeg文件。到目前为止,我能够正确地调整图像的大小。但是我不能压缩图像(降低图像质量)。我的代码如下 float tmph =width2* sourceSize.height/sourceSize.width; NSSize outputSize = NSMakeSize(width2, tmph); NSImage *anImage = [self scaleImage:sourceImage toSize:outputSize]; //com

我正在编写一个小型Mac应用程序来调整和压缩jpeg文件。到目前为止,我能够正确地调整图像的大小。但是我不能压缩图像(降低图像质量)。我的代码如下

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
是我用来调整图像大小的函数。这很有效。在这段代码中,我有两行注释<代码>NSDictionary*选项…line和
NSData*dataToWrite…
line是我添加以获得压缩的两行。但是,无论有没有这两行,我都会得到相同大小的文件


我怎样才能让它工作?有什么建议吗?

您正在将格式类型设置为NSPNGFileType。如果要使用JPEG压缩图像,请将其设置为NSJPEGFileType,如下所示

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