如何将 NSImage 保存为某个目录中的新文件(png、jpg...)?
最佳答案
你可以像这样向 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”的调用至关重要,否则您可能无法获得有效的图像。
关于cocoa - 如何将 NSImage 保存为新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3038820/