在swift中从给定路径初始化图像?

时间:2014-11-04 13:39:22

标签: objective-c macos swift xcode6

我在目标c

中有这个代码
selectedImage = [[NSImage alloc] initWithContentsOfFile:[_thePath path]];

if (selectedImage.size.width < selectedImage.size.height) {
    imageProportion =selectedImage.size.height /selectedImage.size.width ;
    [selectedImage setSize:NSMakeSize(690.0, 690.0* imageProportion )];
} else{
    imageProportion =selectedImage.size.width /selectedImage.size.height ;
    [selectedImage setSize:NSMakeSize(690.0* imageProportion, 690.0)];
}
[_imageEditorWindow orderFront:nil];
[_imageViewEditor setFrameSize:NSMakeSize(selectedImage.size.width, selectedImage.size.height)];
initialImageSizeH = selectedImage.size.height ;
initialImageSizeW = selectedImage.size.width ;
[_imageViewEditor setImage:selectedImage];
[_imageViewEditor setFrameOrigin:NSMakePoint(45, 35)];

如果我在Swift中编写此代码,使用playground但我收到错误:

var selectedImage = NSImage(byReferencingURL: NSURL (string: "/Users/admin/Desktop/10658771_575156615924178_8253607361793017933_o.jpg")!)

2014-11-04 15:32:37.582 MyPlayground [2327:701632] CFURLCopyResourcePropertyForKey失败,因为它传递了这个没有方案的URL:/Users/admin/Desktop/10658771_575156615924178_8253607361793017933_o.jpg 11月15日15:32:37 imac.inf.ucv.local MyPlayground [2327]:ImageIO:CGImageDestinationFinalize图像目的地必须至少有一个图像 2014-11-04 15:32:37.592 MyPlayground [2327:701632] CGImageDestinationFinalize输出类型&#39; public.tiff&#39;

如果我使用此代码:

var selectedImage = NSImage(byReferencingFile: "/Users/admin/Desktop/10658771_575156615924178_8253607361793017933_o.jpg")

ov 4 15:34:56 imac.inf.ucv.local MyPlayground [2331]:ImageIO:CGImageDestinationFinalize图像目的地必须至少有一个图像 2014-11-04 15:34:56.014 MyPlayground [2331:701825] CGImageDestinationFinalize输出类型失败&#39; public.tiff&#39;

那么,出了什么问题?这个错误说我的文件不是图像?

谢谢,对不起我的英语!

1 个答案:

答案 0 :(得分:0)

正在寻找图像的TIFF表示。尝试向NSBitmapImageRep添加NSImage。我最近遇到过这个问题,发现创建NSBitmapImageRep并将其添加到NSImage表示已清除。

假设图像是NSImage实例

let cg = image.CGImageForProposedRect(nil, context: nil, hints: nil)!
let rep = NSBitmapImageRep(CGImage: cg)
image.addRepresentation(self.bitmapRep)

尝试一下,看看它是否效果更好。现在你的方法应该能够从图像中获得TIFF表示。