Как сохранить NSImage как новый файл

Как я могу сохранить NSImage как новый файл (png, jpg...) в определенном каталоге?

73
задан Martin G 8 October 2015 в 09:59
поделиться

2 ответа

Сделайте что-нибудь вроде этого:

NSBitmapImageRep *imgRep = [[image representations] objectAtIndex: 0];
NSData *data = [imgRep representationUsingType: NSPNGFileType properties: nil];
[data writeToFile: @"/path/to/file.png" atomically: NO];
49
ответ дан 24 November 2019 в 12:06
поделиться

Вы можете добавить категорию к NSImage следующим образом

@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

Вызов "TIFFRepresentation" необходим, иначе вы можете не получить корректное изображение.

161
ответ дан 24 November 2019 в 12:06
поделиться
Другие вопросы по тегам:

Похожие вопросы: