如何将数据转换为JPEG格式?

时间:2010-09-13 07:08:51

标签: objective-c cocoa jpeg nsimage

我有这段代码:

NSImage * strImage = [[NSImage alloc]initWithContentsOfFile:ImageFilePath] ;
NSData *imageData = [strImage TIFFRepresentation];

我需要的是将imageData转换为JPEG格式。我希望这与QImage save()的工作方式相同。

为了让您了解save()的工作原理,我会给您一个链接: http://doc.qt.nokia.com/4.6/qimage.html#save

请帮帮我。

1 个答案:

答案 0 :(得分:13)

来自CocoaDev ...如果您在创建后使用NSImage执行任何操作:

NSData *imageData = [image TIFFRepresentation];
NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:imageData];
NSNumber *compressionFactor = [NSNumber numberWithFloat:0.9];
NSDictionary *imageProps = [NSDictionary dictionaryWithObject:compressionFactor
                                         forKey:NSImageCompressionFactor];
imageData = [imageRep representationUsingType:NSJPEGFileType properties:imageProps];
[imageData writeToFile:filename atomically:YES];

如果你之前没有对NSImage做任何其他事情:

NSArray *representations = [myImage representations];
NSNumber *compressionFactor = [NSNumber numberWithFloat:0.9];
NSDictionary *imageProps = [NSDictionary dictionaryWithObject:compressionFactor
                                         forKey:NSImageCompressionFactor];
NSData *bitmapData = [NSBitmapImageRep representationOfImageRepsInArray:representations 
                                       usingType:NSJPEGFileType 
                                       properties:imageProps];    
[bitmapData writeToFile:filename atomically:YES];