NSImage initWithContentsOfFile返回nil

时间:2014-10-28 22:22:17

标签: objective-c xcode macos cocoa osx-yosemite

您好我正在尝试从文件中将图像加载到NSImage,但aImage总是为零。我在这里做错了什么?

NSImage * aImage = [[NSImage alloc]initWithContentsOfFile: @"/Users/Thilina/Desktop/Other/20140818_163933_Fotor_Collage.jpg" ];
[imgPic setImage:aImage];

1 个答案:

答案 0 :(得分:0)

这是一个例子。

- (void)getMyImage {
    NSImage *img = [self getImage:filePath];
}

- (NSImage *)getImage:(NSString *)path {
    NSArray *imageReps = [NSBitmapImageRep imageRepsWithContentsOfFile:path];
    NSInteger width = 0;
    NSInteger height = 0;
    for (NSImageRep * imageRep in imageReps) {
        if ([imageRep pixelsWide] > width) width = [imageRep pixelsWide];
        if ([imageRep pixelsHigh] > height) height = [imageRep pixelsHigh];
    }
    NSImage *imageNSImage = [[NSImage alloc] initWithSize:NSMakeSize((CGFloat)width, (CGFloat)height)];
    [imageNSImage addRepresentations:imageReps];
    return imageNSImage;
}