Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a NSImage as a new file

How can I save a NSImage as a new file (png, jpg, ...) in a certain directory?

like image 381
burki Avatar asked Jun 14 '10 16:06

burki


2 Answers

You could add a category to NSImage like this

@interface NSImage(saveAsJpegWithName) - (void) saveAsJpegWithName:(NSString*) fileName; @end  @implementation NSImage(saveAsJpegWithName)  - (void) saveAsJpegWithName:(NSString*) fileName {     // Cache the reduced image     NSData *imageData = [self TIFFRepresentation];     NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:imageData];     NSDictionary *imageProps = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:1.0] forKey:NSImageCompressionFactor];     imageData = [imageRep representationUsingType:NSJPEGFileType properties:imageProps];     [imageData writeToFile:fileName atomically:NO];         }  @end 

The call to "TIFFRepresentation" is essential otherwise you may not get a valid image.

like image 155
Pegolon Avatar answered Nov 16 '22 01:11

Pegolon


Do something like this:

NSBitmapImageRep *imgRep = [[image representations] objectAtIndex: 0]; NSData *data = [imgRep representationUsingType: NSPNGFileType properties: nil]; [data writeToFile: @"/path/to/file.png" atomically: NO]; 
like image 39
garph0 Avatar answered Nov 16 '22 01:11

garph0