views:

244

answers:

2

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

Thank you for answering my "noobish" question.

+3  A: 

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];
garph0
You should get the bitmap image rep in a more reliable way than assuming that it is the first representation. You also cannot assume that there is one; if the image was loaded from a PDF, for example, then there will be an NSPDFImageRep, not an NSBitmapImageRep.
Peter Hosey
This is buggy hack. See below for regular answer.
Eonil
+2  A: 

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.

Pegolon