objective-cmacoscocoansimagensimagerep

Best practice of storing and retrieving an NSImage in binary


I'm working with NSImage's and want to store them in a Core Data binary object. I got things working, but I read a lot of different ways that are using NSImageRep to do this. Currently I'm doing the following:

Creating binary data from an image

- (NSData *)createBinaryWithImage:(NSImage *)image {
    return [image TIFFRepresentation];
}

Creating an image from binary data

- (NSImage *)createImageWithBinaryData:(NSData *)binaryData {
    return [[NSImage alloc] initWithData:binaryData];
}

Is this an acceptable and valid way or is there a better way ?


Solution

  • I would typically use TIFFRepresentation if you're just trying to round-trip for yourself. It's what NSImage likes to work with and often doesn't require any expensive conversion step. It's pretty close to "just dump what we got here." It's particularly good if you don't know whether the data is compressed or uncompressed, since it can handle either natively.

    Generally converting to an NSBitmapImageRep and then from there to some other format (with representationUsingType:properties:) is valuable if you want to inspect or manipulate the pixels before saving. But I don't think I'd create an image rep just to convert it to data. The whole point of an NSImage to manage a group of NSImageRep and choose the right one for each purpose. You generally should just let it handle that part.

    Today PNG is much more popular than TIFF, so if you're writing files outside of your own data store, PNG would be a more common choice (and you'd need to work through NSImageRep to get there). JPEG of course is a whole different thing since it's lossy, and so should seldom be used for anything but export.