2010-09-13 54 views
2

我有這樣的代碼:如何將數據轉換爲JPEG格式?

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

請幫助我。

+0

是的,我問一個新的問題:) – 2010-09-15 06:13:39

回答

12

從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]; 
+0

非常感謝,它的工作原理。 – 2010-09-13 08:31:43

+0

但是浪費多少時間;你得到的圖像TIFF表示,但立即創建一個圖像代表!如果您的源圖像已有位圖表示,請使用該圖像。 – 2010-09-13 09:06:08

+1

@Mike:這在所有情況下都不起作用,請參閱CocoaDev鏈接。 – 2010-09-13 09:26:21