Cocoa 使用 NSImage 进行图像压缩
Cocoa Image Compression with NSImage
我正在编写一个 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 *options.....
行和 NSData *dataToWrite....
行是我为获得压缩而添加的两行。但是无论有没有这两行,我得到的文件大小都是一样的。
我怎样才能让它工作?有什么建议吗?
您正在将格式类型设置为 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];
我正在编写一个 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 *options.....
行和 NSData *dataToWrite....
行是我为获得压缩而添加的两行。但是无论有没有这两行,我得到的文件大小都是一样的。
我怎样才能让它工作?有什么建议吗?
您正在将格式类型设置为 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];