Jak zapisać UIImage do pliku?


Odpowiedzi:


129

Oczywiście możesz tworzyć podfoldery w folderze dokumentów swojej aplikacji. Zwykłeś NSFileManagerto robić.

Używasz UIImagePNGRepresentationdo konwersji obrazu na NSData i zapisywania go na dysku.

// Create path.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Image.png"];

// Save image.
[UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];

Nawiasem mówiąc, dane podstawowe nie mają nic wspólnego z zapisywaniem obrazów na dysku.


Tracisz wszystkie informacje o orientacji, używając UIImagePNGRepresentation.

1
więc jak mogę zapisywać obrazy bez utraty informacji?
Pol

@Pol możesz zapisać go jako UIImageJPEGRepresentation lub samodzielnie ustalić orientację, różne rozwiązania w linku stackoverflow.com/questions/3554244/ ...
user1210182

27

W Swift 3:

// Create path.
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let filePath = "\(paths[0])/MyImageName.png"

// Save image.
UIImagePNGRepresentation(image)?.writeToFile(filePath, atomically: true)

3
Już nieważne - musisz użyć.write() throws
Andrew K


17

Powyższe są przydatne, ale nie odpowiadają na pytanie, jak zapisać w podkatalogu lub pobrać obraz z UIImagePicker.

Najpierw musisz określić, że kontroler implementuje delegata selektora obrazu w pliku kodu .m lub .h, na przykład:

@interface CameraViewController () <UIImagePickerControllerDelegate>

@end

Następnie zaimplementujesz metodę imagePickerController: didFinishPickingMediaWithInfo: delegata, w której możesz pobrać zdjęcie z selektora obrazów i zapisać je (oczywiście możesz mieć inną klasę / obiekt, który obsługuje zapisywanie, ale pokażę tylko kod wewnątrz metody):

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

Jeśli chcesz zapisać jako obraz JPEG, ostatnie 3 wiersze będą wyglądać następująco:

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

12
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")

6
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:path atomically:YES];

gdzie ścieżka to nazwa pliku, do którego chcesz go zapisać.


4

Najpierw powinieneś pobrać katalog Dokumenty

/* create path to cache directory inside the application's Documents directory */
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"fileName"];

Następnie należy zapisać zdjęcie do pliku

NSData *photoData = UIImageJPEGRepresentation(photoImage, 1);
[photoData writeToFile:filePath atomically:YES];

4

W Swift 4.2:

// Create path.
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
if let filePath = paths.first?.appendingPathComponent("MyImageName.png") {
    // Save image.
    do {
       try image.pngData()?.write(to: filePath, options: .atomic)
    } catch {
       // Handle the error
    }
}

2

W Swift 4:

// Create path.
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
if let filePath = paths.first?.appendingPathComponent("MyImageName.png") {
    // Save image.
    do {
       try UIImagePNGRepresentation(image)?.write(to: filePath, options: .atomic)
    }
    catch {
       // Handle the error
    }
}
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.