cocoa - 如何将 NSImage 保存为新文件

标签 cocoa image macos file nsimage

如何将 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/

相关文章:

swift - 如何为所有正在运行的应用程序添加监听器

ios - Core Text - 字形高度

objective-c - Lego Mindstorm NXT、Cocoa 和 HiTechnic 传感器

html - div 中的图像在图像下方有额外的空间

c - 在 C 中查找 .bmp 图像的宽度和高度

Git:*你*如何使用它?/傻瓜教程

xcode - 如何在 Xcode mac 应用程序的选项卡 View 中放置对象?

objective-c - 如何使用 NSBrowser 中选定单元格的路径更新 NSPathControl

ios - 图片搜索引擎的使用

c++ - Visual Studio Code c++11 扩展警告