Search code examples
cocoansurlnsimagenspasteboard

NSImage → NSURL → Custom Object


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];
    }

Solution

  • 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

    1. Change you 'process' to accept NSImage.
    2. Write the NSImage to a temporary file and use that file path.