This is probably a n00b question so I apologize in advance. I'm working with NSImage for the first time and basically I need to simply take a picture that is in my Resources folder, and have it display in an NSView/NSImageWell when a button is clicked.
NSImage *image = [[NSImage alloc] initWithContentsOfFile:#"tiles.PNG"];
if ( [image isValid] ) {
NSImageView *view = [[NSImageView alloc] init];
[selection setImage:image];
[selection setImageScaling:NSScaleProportionally];
}
else {
--- This line of code always activates meaning my image isn't valid
}
My only guess is that I am getting the path wrong to the image file and I have looked all over for the right way to access it. Another guess is that I have my code wrong. Anybody familiar with this? Thanks!
I work a lot more with the iPhone, but initWithContentsOfFile seems to require a full/relative path, which I assume tiles.PNG wouldn't fulfill.
I'd use the class method imageNamed:(NSString *)name, which will search your bundle for you.
You should use NSBundleManger to locate the image like so:
NSBundle *mb=[NSBundle mainBundle];
NSString *fp=[mb pathForResource:#"titles" ofType:#"PNG"];
UIImage *img=[UIImage imageWithContentsOfFile:fp];
That way you don't have to mess with internal paths yourself. Otherwise, you have to have the path relative to the final built product which is hard to create and maintain.
Related
I try to get a file icon and to set it back to the same file (goal is to have overlay, but I first want to have this one work):
NSImage *img=[[NSWorkspace sharedWorkspace] iconForFile:#"MyFilePath"];
NSLog(#"x=%.f",img.size.width); // Result=32
[[NSWorkspace sharedWorkspace] setIcon:img forFile:#"MyFilePath" options:0];
-> Result is that my file gets a standard Finder icon instead of keeping its own icon. Anything I am doing wrong ?
Try using it like this:
[[NSWorkspace sharedWorkspace]
setIcon: [[NSImage alloc] initWithContentsOfFile:#"MyFilePath"]
forFile: #"MyFilePath"
options: 0];
You need to to load the icon/image into memory first.
EDIT: Answer updated to provide additional information in regards to
the comment below.
"how can I keep the image in memory to "play" with it before reassigning it?"
The NSImage that gets allocated into memory from your specified path can be manipulated in just about any possible way once it's been loaded. You'll want to thoroughly read the NSImage Class Reference to gain a real understanding of what it does and how use it's methods. For this particular scenario you'll want to be able have a named variable assigned from the icon you load.
Only one change needs to happen with the code above to make it work:
NSImage *iconImage = [[NSImage alloc] initWithContentsOfFile:#"MyFilePath"];
[[NSWorkspace sharedWorkspace]
setIcon: iconImage
forFile: #"MyFilePath"
options: 0];
NSLog(#"iconImage: %#",iconImage);
The slight change essentially assigns the variable iconImage from the NSImage icon; everything else stays the same. The NSLog will give you a very quick glimpse at properties associated with iconImage — where you take it from there is really up to your coding ability and creativity.
Iam trying to draw a TIFF image from a string in XCode to display it in the dock.
The TIFF-image is obtained through an AppleScript that interacts with Spotify:
tell application "Spotify"
set aTrackArtwork to artwork of current track
end tell
The string that I receive is something like this:
TIFF4D4D002A00041EB821585D22595E215..
How can I draw an image from this binary code? My current code (which is a proof-of-concept) looks like this:
NSImage *myImage = [[NSImage alloc] init];
myImage = [NSImage imageNamed:#"ikoner"];
[NSApp setApplicationIconImage:myImage];
Is there any way to draw the image within the myImage object?
And, is there any easier way to obtain this information directly in my Xcode project without having to rely on the applescript?
My goal is to create a simple application that gets the current playing song and display it's album art in the dock.
I appreciate all answers that may or may not lead me closer to the answer!
This is fairly simply with the Scripting Bridge.
First, generate Spotify.h in the Terminal:
sdef /Applications/Spotify.app | sdp -fh --basename Spotify
Then, import the header file into your project, then link to ScriptingBridge.framework.
Finally, grab the image and put it in the Dock. Here's a basic example:
#import "Spotify.h"
// Get the image from Spotify
SpotifyApplication *spotify = [SBApplication applicationWithBundleIdentifier:#"com.spotify.client"];
NSImage *coverArt = spotify.currentTrack.artwork;
// Create an image view and put it in the Dock
NSImageView *imageView = [[NSImageView alloc] initWithFrame:NSZeroRect];
imageView.image = coverArt;
NSDockTile *dock = [[NSApplication sharedApplication] dockTile];
dock.contentView = imageView;
[dock display];
I'm not to familiar with the Spotify api, however something like this seems like it would work (convert your string into an NSData object:
[[NSImage alloc] initWithData:]
I have checked out a few similar questions and didn't find the answer to my question.
First part of the question is how to write relative path of file. I didn't get this work but let me move the second part at the moment. Since I couldn't get relative path work, so I tried absolute path. Here is the code I use:
NSString *path = [NSString stringWithFormat:#"/Users/my.name/Documents/TestFour/TestFour/Library/file%d.txt", i]; //where i is 1 or 2
//NSString *path = [NSString stringWithFormat:#"./TestFour/Library/file%d.txt", i]; //this relative path didn't work, although TestFour.xcodeproj and TestFour are in the same directory and TestFour has child directory Library and xxx.h and xxx.m files
NSString *spath = [path stringByStandardizingPath];
NSLog(#"file is %#", spath);
if (spath) {
NSString *myText = [NSString stringWithContentsOfFile:spath encoding:NSUTF8StringEncoding error:nil];
//continue, and I got myText ....
Now I have a jpg file, say myPic.jpg, in the same directory as above file1.txt, i.e., in the Library folder. I want to load this image into a UIImageView, here is my code, but it failed.
NSString *path = #"/Users/my.name/Documents/TestFour/TestFour/Library/myPic.jpg";
NSString *spath = [path stringByStandardizingPath];
[self._bgView setImage:[UIImage imageNamed:spath]];
However, I tried a web-based image, which BTW from another related thread, and it worked:
[self._bgView setImage:[[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://farm4.static.flickr.com/3092/2915896504_a88b69c9de.jpg"]]]];
So I'm confused why I could read the_same_folder_file1.txt but not load the_same_folder_myPic.jpg
And back to the first part, why my relative path didn't work? Not sure if this is related, I was asked and selected the default setting (Group or something like this) when I drag this and other jpg into project. I don't know if I need drag this jpg into the project, but the code didn't work either way, before and after dragging.
[UIImage imageNamed] will load the file with the given name from the app bundle; what you want is [UIImage imageWithContentsOfFile] (reference).
Also you need to understand that relative file paths work based on the process's current working directory. Do you know what that is? If not then you can log it using something like:
char cwd[1024];
getcwd(cwd, sizeof(cwd));
NSLog(#"cwd='%s'", cwd);
(You may need to #import <unistd.h>).
Perhaps that will help you with your relative path issue.
I wondering how you would retrieve the path of the file that a user has dragged and dropped into a cocoa application. For example: User drags a file named test from his/her desktop. Then the cocoa application would say: Users/currentusername/Desktop/test
Thanks for the help!
I just downloaded Apple's "CocoaDragAndDrop" sample code and tried it out.
When I drag in a PNG file from the Finder into the running app, the title of the window changes to the path of the image that was dragged in.
Looking inside the sample code, I can see a file URL is included in the Pasteboard:
//if the drag comes from a file, set the window title to the filename
fileURL=[NSURL URLFromPasteboard: [sender draggingPasteboard]];
[[self window] setTitle: fileURL!=NULL ? [fileURL absoluteString] : #"(no name)"];
Try this technique in your own code and modify it for taste.
The accepted answer is no longer working with Xcode 6.
I've found this methode to get the same result:
NSURL*fileURL = [NSURL URLFromPasteboard: [sender draggingPasteboard]];
NSString *filePath = [fileURL path];
[[self window] setTitle:filePath];
Currently working on developing a similar interface, I’ve understood that the OP had asked for path, not URL retrieval. It seems the suggested OS X 10.10 (XCode6) workaround for the accepted answer has issues in refusing to drag and drop content between windows.
However, avoiding declaring NSString *filePath, but simply substituting the [fileURL absoluteString] method with [fileURL path] method in line 175 of DragDropImageView.m of the suggested sample code instead, seems to solve it:
fileURL=[NSURL URLFromPasteboard: [sender draggingPasteboard]];
[[self window] setTitle: fileURL!=NULL ? [fileURL path] : #"(no name)"];
It compiles and runs as devised in Xcode4 through Xcode6, SDK 10.8-10.10, AFAICT.
Hope this can help.
My application is trying to create custom objects from NSImage objects (coming from the pasteboard) but my current process only takes in image URLs.
I'd like to avoid major changes at this point so I was wondering if there was any way to get the URL of an NSImage (it seems like a reasonable expectation since one can initialize an NSImage from a URL)
Thanks.
EDIT (answer)
I went a slightly different route. Instead of getting the content of the pasteboard as an array of NSImage, I simply got it as an array of NSURL. I can then feed those into my process.
NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
NSArray *classArray = [NSArray arrayWithObject:[NSURL class]];
NSDictionary *options = [NSDictionary dictionary];
BOOL ok = [pasteboard canReadObjectForClasses:classArray options:options];
if (ok) {
NSArray *URLs = [pasteboard readObjectsForClasses:classArray options:options];
}
Quote by BlazingFrog:
(it seems like a reasonable expectation since one can initialize an NSImage from a URL)
Lets say I initialize a NSString by using:
NSString * theString = [NSString initWithContentsOfURL: encoding: error: ];
I'm sure it's not possible to retrieve the original NSURL from the NSString.
And I'm quite sure the same applies to NSImage. (Actually, completely sure.)
Indeed NSImage can be initialized by initWithContentsOfURL:.
But it can also be initialized by initWithData: or initWithPasteboard:.
The NSURL is no strict requirement for initializing a NSImage.
In other words, the NSImage might be initialized without using a URL.
The NSImage is simply a container for image representations.
Quote by Apple:
An NSImage object manages a group of image representations.
Solutions
Change you 'process' to accept NSImage.
Write the NSImage to a temporary file and use that file path.
If the image is being delivered via the standard pasteboard (i.e. the copy/paste mechanism) then there is no way to refer to it by URL because it might not have one. For instance, if you open a document in Word or Pages, select an image and copy it there is no possible way to create a URL reference to that image. It's on the pasteboard but not in the file system in a form you can access.
I think that you're going to have to modify your code to handle NSImage objects directly.