Greshi Gupta
Greshi Gupta

Reputation: 831

How to convert data to JPEG format?

I have this code:

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

What I require is to convert imageData into JPEG format. I want this to work the same as QImage save() does.

So that you can see how save() works, I will give you a link: http://doc.qt.nokia.com/4.6/qimage.html#save

Please help me.

Upvotes: 2

Views: 7024

Answers (1)

Georg Fritzsche
Georg Fritzsche

Reputation: 98984

From CocoaDev... If you do anything with the NSImage after creating it:

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

If you don't really do anything else with the NSImage before:

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

Upvotes: 15

Related Questions