2014-04-24 22 views
9

Sto creando un plist dalla mia app OSX che contiene alcune immagini. Sto scrivendo l'immagine:NSImage to NSData, then to UIImage

[NSKeyedArchiver archivedDataWithRootObject:self.someImage] 

Poi Sto usando questo file plist come modello per iOS, ma qui non riesco a convertire il file in UIImage e né NSImage (come questo è solo per OSX).

sto ottenendo questo errore:

* Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: '* -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (NSImage)'

si prega di suggerire a me un modo per eseguire quanto sopra.

risposta

16

OS X:
Invece di usare NSKeyedArchiver per convertire un NSImage-NSData, utilizzare NSImage s' TIFFRepresentation metodo:

NSData *imageData = [self.someImage TIFFRepresentation]; 
// save imageData to file 

iOS:
leggere i dati di immagine dal file, quindi convertirlo in UIImage usando il costruttore di convenienza +imageWithData: di UIImage:

NSData *imageData = ...; // load imageData from file 
UIImage *image = [UIImage imageWithData: imageData]; 
+1

Penso che tu voglia 'TIFFRepresentation' qui –

+0

Oops , corretto. Grazie! –

3

È necessario creare un NSBitmapImageRep e quindi salvare che, quindi leggere il NSData-UIImage con +[UIImage imageWithData:]:

Prima in OS X, salvare i dati:

NSString *filepath; 
NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithContentsOfFile:filepath]; 

NSData *data = [imageRep representationUsingType:NSPNGFileType properties:nil]; 
// Save the data 

Si potrebbe anche usare imageRepWithData: se hai già NSData dell'immagine - quanto sopra lo caricherà da un file (come puoi fare also fare con NSImage).

Poi in iOS:

NSData *data; // Load from a file 
UIImage *image = [UIImage imageWithData:data]; 

Vedi here per gli altri tasti consentite per il dizionario in representationUsingType:properties:.

+1

UIImagePNGRepresentation() viene utilizzata in modo non corretto nel codice precedente: La funzione serve per convertire un esempio UIImage in un oggetto NSData, non per convertire NSData in una UIImage. Vedi: https://developer.apple.com/library/ios/documentation/uikit/reference/UIKitFunctionReference/Reference/reference.html#//apple_ref/c/func/UIImagePNGRepresentation –

-1

È possibile convertire un NSImage in NSData utilizzando la mela API integrata come segue:

UIImage *MyImage = [UIImage imageNamed:@"WhateverDir/MyImage.png"]; 
NSData *MyImageData = UIImagePNGRepresentation(MyImage); 
+1

Stai convertendo UIImage qui (ad esempio iOS) non NSImage (cioè OS X) –