Zapisz obraz w folderze Dokumenty aplikacji z UIView na IOS

Mam interfejs UIImageView, który pozwala użytkownikowi na umieszczenie i przytrzymanie obrazu, dopóki nie zostanie zapisany. Problem w tym, że nie mogę dowiedzieć się, jak faktycznie zapisać i odzyskać obraz, który umieściłem w widoku.

Pobrałem i umieściłem obrazek w UIImageView TAK:

//Get Image 
- (void) getPicture:(id)sender {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = (sender == myPic) ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    [self presentModalViewController:picker animated:YES];
    [picker release];
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage (UIImage *)image editingInfo:(NSDictionary *)editingInfo {
    myPic.image = image;
    [picker dismissModalViewControllerAnimated:YES];
}

Wyświetla wybrany obraz w moim UIImageView dobrze, ale nie mam pojęcia, jak go zapisać. Zapisuję wszystkie pozostałe fragmenty widoku (głównie UITextfield) w Core Data. Szukałem i przeszukałem i wypróbowałem wiele bitów kodu, które ludzie zasugerowali, ale albo nie wprowadzam kodu poprawnie, albo te sugestie nie działają w sposób, w jaki mam skonfigurowany kod. To pewnie ten pierwszy. Chciałbym zapisać obraz w UIImageView za pomocą tej samej akcji (przycisk Zapisz), której używam, aby zapisać tekst w UITextFields. Oto jak zapisuję informacje o UITextField:

// Handle Save Button
- (void)save {

    // Get Info From UI
    [self.referringObject setValue:self.myInfo.text forKey:@"myInfo"];

Jak powiedziałem wcześniej, próbowałem kilku metod, aby to zadziałało, ale nie mogę tego zrozumieć. Po raz pierwszy w życiu chciałem wyrządzić krzywdę przedmiotowi nieożywionemu, ale udało mi się powstrzymać.

Chciałbym móc zapisać obraz, który użytkownik umieszcza w UIImageView w folderze Dokumentów aplikacji, a następnie móc go pobrać i umieścić w innym UIImageView do wyświetlania, gdy użytkownik wypchnie ten widok na stos. Każda pomoc jest bardzo mile widziana!

Author: Fangming, 2011-07-25

5 answers

Wszystko w porządku, Stary. Nie krzywdź siebie ani innych.

Prawdopodobnie nie chcesz przechowywać tych obrazów w podstawowych danych, ponieważ może to wpłynąć na wydajność, jeśli zestaw danych będzie zbyt duży. Lepiej zapisać obrazy do plików.

NSData *pngData = UIImagePNGRepresentation(image);

To wyciąga dane PNG z przechwyconego obrazu. Stąd możesz zapisać go do pliku:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory 
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"image.png"]; //Add the file name
[pngData writeToFile:filePath atomically:YES]; //Write the file
Czytanie tego później działa tak samo. Zbuduj ścieżkę tak, jak zrobiliśmy to powyżej:
NSData *pngData = [NSData dataWithContentsOfFile:filePath];
UIImage *image = [UIImage imageWithData:pngData];

To, co prawdopodobnie będziesz chciał zrobić, to Utwórz metodę, która tworzy ciągi ścieżek, ponieważ nie chcesz, aby ten kod był wszędzie zaśmiecany. Może to wyglądać tak:

- (NSString *)documentsPathForFileName:(NSString *)name
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);  
    NSString *documentsPath = [paths objectAtIndex:0];

    return [documentsPath stringByAppendingPathComponent:name]; 
}
Mam nadzieję, że to pomoże.
 328
Author: Danilo Campos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-26 07:01:43

Wersja Swift 3.0

let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString

let img = UIImage(named: "1.jpg")!// Or use whatever way to get the UIImage object
let imgPath = URL(fileURLWithPath: documentDirectoryPath.appendingPathComponent("1.jpg"))// Change extension if you want to save as PNG

do{
    try UIImageJPEGRepresentation(img, 1.0)?.write(to: imgPath, options: .atomic)//Use UIImagePNGRepresentation if you want to save as PNG
}catch let error{
    print(error.localizedDescription)
}
 3
Author: Fangming,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-23 18:49:22

W Języku Swift:

let paths: [NSString?] = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .LocalDomainMask, true)
if let path = paths[0]?.stringByAppendingPathComponent(imageName) {
    do {
        try UIImagePNGRepresentation(image)?.writeToFile(path, options: .DataWritingAtomic)
    } catch {
        return
    }
}
 0
Author: NatashaTheRobot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-21 09:26:36

To jest odpowiedź Fangming Ning dla Swift 3/4, zaktualizowany o zalecaną i bardziej szybką metodę do pobierania ścieżki katalogu dokumentu i z lepszą dokumentacją. Podziękowania dla Fangming Ning za nową metodę.

guard let documentDirectoryPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
    return
}

//Using force unwrapping here because we're sure "1.jpg" exists. Remember, this is just an example.
let img = UIImage(named: "1.jpg")!

// Change extension if you want to save as PNG.
let imgPath = URL(fileURLWithPath: documentDirectoryPath.appendingPathComponent("1.jpg").absoluteString)

do {
    //Use UIImagePNGRepresentation if you want to save as PNG.
    //.atomic is just an example here, check out other writing options as well. (see the link under this example)
    //(atomic writes data to a temporary file first and sending that file to its final destination)
    try UIImageJPEGRepresentation(img, 1)?.write(to: imgPath, options: .atomic)
} catch {
    print(error.localizedDescription)
}

Sprawdź wszystkie możliwe opcje zapisu Danych tutaj.

 0
Author: Tamás Sengel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-03 11:58:00

Swift 4 z rozszerzeniem

extension UIImage{

func saveImage(inDir:FileManager.SearchPathDirectory,name:String){
    guard let documentDirectoryPath = FileManager.default.urls(for: inDir, in: .userDomainMask).first else {
        return
    }
    let img = UIImage(named: "\(name).jpg")!

    // Change extension if you want to save as PNG.
    let imgPath = URL(fileURLWithPath: documentDirectoryPath.appendingPathComponent("\(name).jpg").absoluteString)
    do {
        try UIImageJPEGRepresentation(img, 0.5)?.write(to: imgPath, options: .atomic)
    } catch {
        print(error.localizedDescription)
    }
  }
}

Przykład użycia

 image.saveImage(inDir: .documentDirectory, name: "pic")
 -1
Author: levin varghese,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-19 07:26:17