如何使用Cocoa压缩jpeg图像?

时间:2009-11-20 21:29:45

标签: cocoa macos nsimage nsbitmapimagerep nsimagerep

我有一个jpeg图像,我希望能够使用Cocoa / Core Image / Core Graphics逐步压缩它。例如,我有A.jpg(3MB),我压缩A并获得B.jpg(1MB),压缩B并获得C.jpg(400KB),依此类推,直到图像不再被压缩为止。

我正在尝试使用NSBitmapImageRep representationUsingType:属性而没有太大成功。我使用从压缩图像数据创建的图像代表来尝试进一步压缩,但如果我使用的压缩因子与用于创建初始压缩数据的因子相同,则效果不佳。

以下是我与

进行争论的代码
NSString * fileName = @"largeImage.jpg";

NSLog(@"== Initializing ==\n");

NSData * imageData = [NSData dataWithContentsOfFile:fileName];
NSLog(@"imageData length: %d\n", [imageData length]);

NSImage * image = [[NSImage alloc] initWithData:imageData];
NSBitmapImageRep * bitmapRep = [[image representations] objectAtIndex:0];

NSData * data = [bitmapRep representationUsingType:NSJPEGFileType properties:nil];
NSLog(@"data length: %d\n", [data length]);

NSDictionary * dict = [NSDictionary dictionaryWithObject: [NSNumber numberWithFloat:0.5] forKey:NSImageCompressionFactor];
NSData * data5 = [bitmapRep representationUsingType:NSJPEGFileType properties:dict];
NSLog(@"data5 length: %d\n", [data5 length]);

NSLog(@"== End ==\n\n");

NSLog(@"== Image from Data5 ==\n");
NSImage * imageFromData5 = [[NSImage alloc] initWithData:data5];
NSBitmapImageRep * bitmapRepFromData5 = [[imageFromData5 representations] objectAtIndex:0];

NSData * dataFromImageFromData5 = [bitmapRepFromData5 representationUsingType:NSJPEGFileType properties:nil];
NSLog(@"dataFromImageFromData5 length: %d\n", [dataFromImageFromData5 length]);

dict = [NSDictionary dictionaryWithObject: [NSNumber numberWithFloat:0.5] forKey:NSImageCompressionFactor];
NSData * dataFiveFromImageWithData5 = [bitmapRepFromData5 representationUsingType:NSJPEGFileType properties:dict];
NSLog(@"dataFiveFromImageWithData5 length: %d\n", [dataFiveFromImageWithData5 length]);
NSLog(@"== End ==\n\n");

这是我的结果

> == Initializing ==
> imageData length: 1882694
> data length: 1888365
> data5 length: 1102461
> == End ==

> == Image from Data5 ==
> dataFromImageFromData5 length: 1646137
> dataFiveFromImageWithData5 length: 1102115
> == End ==


Try a different image
> == Initializing ==
> imageData length: 3620257
> data length: 2889458
> data5 length: 1404750
> == End ==

> == Image from Data5 ==
> dataFromImageFromData5 length: 2007951
> dataFiveFromImageWithData5 length: 1405398
> == End ==

1 个答案:

答案 0 :(得分:4)

您需要每次都减少因子。使用相同的质量等级重新压缩未编辑的JPEG图像实际上并没有多大改变结果,这可以解释为什么你没有看到任何尺寸减小。

(如果你想确保质量不会降低到超过必要的程度,那么使用递减因子一遍又一遍地重新压缩原始图像是有意义的,而不是像你的例子那样链接它们。)