Se ho un UIImage
da un imagePicker, come posso salvarlo in una sottocartella nella directory dei documenti?Come si salva un UIImage in un file?
risposta
dovete construct a representation of your image as a particular format (diciamo, JPEG o PNG), e quindi chiamare writeToFile:atomically:
sulla rappresentazione:
UIImage *image = ...;
NSString *path = ...;
[UIImageJPEGRepresentation(image, 1.0) writeToFile:path atomically:YES];
Naturalmente è possibile creare sottocartelle nella cartella documenti della vostra applicazione. Si usa NSFileManager
per farlo.
È possibile utilizzare UIImagePNGRepresentation
per convertire l'immagine in NSData e salvarla su disco.
// Create path.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Image.png"];
// Save image.
[UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
Core Data non ha nulla a che fare con il salvataggio delle immagini su disco.
In primo luogo si dovrebbe ottenere la directory Documenti
/* create path to cache directory inside the application's Documents directory */
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"fileName"];
allora si dovrebbe salvare la foto nel file
NSData *photoData = UIImageJPEGRepresentation(photoImage, 1);
[photoData writeToFile:filePath atomically:YES];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:path atomically:YES];
dove percorso è il nome del file che si desidera scrivere a.
Quanto sopra sono utili, ma non rispondono alla tua domanda su come salvare in una sottodirectory o ottenere l'immagine da un UIImagePicker.
In primo luogo, è necessario specificare che il controller implementa delegato immagine di picker, sia in .m o .h file di codice, come ad esempio:
@interface CameraViewController() <UIImagePickerControllerDelegate>
@end
Poi si implementano imagePickerController del delegato: didFinishPickingMediaWithInfo: metodo, che è dove è possibile ottenere la fotografia dal selettore immagine e salvarla (naturalmente, si può avere un'altra classe/oggetto che gestisce il risparmio, ma mi limiterò a mostrare il codice all'interno del metodo):
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// get the captured image
UIImage *image = (UIImage *)info[UIImagePickerControllerOriginalImage];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *imageSubdirectory = [documentsDirectory stringByAppendingPathComponent:@"MySubfolderName"];
NSString *filePath = [imageSubdirectory stringByAppendingPathComponent:@"MyImageName.png"];
// Convert UIImage object into NSData (a wrapper for a stream of bytes) formatted according to PNG spec
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:filePath atomically:YES];
}
Se vuoi salvare come immagine JPEG, la st 3 linee sarebbero:
NSString *filePath = [imageSubdirectory stringByAppendingPathComponent:@"MyImageName.jpg"];
// Convert UIImage object into NSData (a wrapper for a stream of bytes) formatted according to JPG spec
NSData *imageData = UIImageJPEGRepresentation(image, 0.85f); // quality level 85%
[imageData writeToFile:filePath atomically:YES];
In Swift 3:
// Create path.
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let filePath = "\(paths[0])/MyImageName.png"
// Save image.
UIImagePNGRepresentation(image)?.writeToFile(filePath, atomically: true)
Non più valido - è necessario utilizzare '.write() throws' –
extension UIImage {
/// Save PNG in the Documents directory
func save(_ name: String) {
let path: String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let url = URL(fileURLWithPath: path).appendingPathComponent(name)
try! UIImagePNGRepresentation(self)?.write(to: url)
print("saved image at \(url)")
}
}
// Usage: Saves file in the Documents directory
image.save("climate_model_2017.png")
perdi tutte le informazioni di orientamento utilizzando UIImagePNGRepresentation. –
quindi, come posso salvare le immagini senza perdere informazioni? – Pol