can't open image with NSOpenPanel

假如想象 提交于 2020-01-14 06:04:03

问题


I use below code for open image with NSOpenPanel but doesn't work

//panel=NSOpenPanel
 NSString *imgg = [NSString stringWithFormat:@"%@",panel.URL];
 self.imgUser.image=[NSImage imageNamed:imgg];

回答1:


The problem is that +[NSImage imageNamed:] doesn't load an image by URL. If you read the documentation, it explains what it actually does: it looks for an image stored in the cache under that name, or stored in the app's bundle or AppKit's framework under that filename.

There are a large number of ways to actually open an image by URL. The one you're probably looking for is:

NSImage *image = [[[NSImage alloc] initWithContentsOfURL:panel.URL] autorelease];

Also, as a side issue, the way you're trying to turn a URL into a path is incorrect. If you have an NSURL for file://localhost/Users/user437064/Pictures/mypic.jpg, just converting that to a string just gives you @"file://localhost/Users/user437064/Pictures/mypic.jpg". That isn't a path that you can use with path-based APIs. What you actually want is @"/Users/user437064/Pictures/mypic.jpg", and the way you get that is -[NSURL path]. So "NSString *imgg = [panel.URL path];". But this is irrelevant; unless you need to deal with very old versions of OS X, or out-of-the-way APIs, there's almost always a method that takes a URL for each method that takes a path, and often the path-based ones are deprecated.

As an even farther-off-the-side issue, you don't need stringWithFormat: to convert something to a string; "[panel.URL description]" gives the exact same result as "[NSString stringWithFormat:@"%@", panel.URL]", much more simply and a little more efficiently.



来源:https://stackoverflow.com/questions/10355591/cant-open-image-with-nsopenpanel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!