How do I save a UIImage to a file?

前端 未结 9 856
抹茶落季
抹茶落季 2020-12-07 13:13

If I have a UIImage from an imagePicker, how can I save it to a subfolder in the documents directory?

相关标签:
9条回答
  • 2020-12-07 13:18

    You have to construct a representation of your image as a particular format (say, JPEG or PNG), and then call writeToFile:atomically: on the representation:

    UIImage *image = ...;
    NSString  *path = ...;
    [UIImageJPEGRepresentation(image, 1.0) writeToFile:path atomically:YES];
    
    0 讨论(0)
  • 2020-12-07 13:18

    The above are useful, but they don't answer your question of how to save in a subdirectory or get the image from a UIImagePicker.

    First, you must specify that your controller implements image picker's delegate, in either .m or .h code file, such as:

    @interface CameraViewController () <UIImagePickerControllerDelegate>
    
    @end
    

    Then you implement the delegate's imagePickerController:didFinishPickingMediaWithInfo: method, which is where you can get the photograph from the image picker and save it (of course, you may have another class/object that handles the saving, but I'll just show the code inside the method):

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

    If you want to save as JPEG image, the last 3 lines would be:

    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];
    
    0 讨论(0)
  • 2020-12-07 13:19
    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")
    
    0 讨论(0)
  • 2020-12-07 13:19

    In 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
        }
    }
    
    
    0 讨论(0)
  • 2020-12-07 13:20

    Of course you can create subfolders in the documents folder of your app. You use NSFileManager to do that.

    You use UIImagePNGRepresentation to convert your image to NSData and save that to disk.

    // 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 has nothing to do with saving images to disk by the way.

    0 讨论(0)
  • 2020-12-07 13:34

    First you should get the Documents directory

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

    Then you should save the photo to the file

    NSData *photoData = UIImageJPEGRepresentation(photoImage, 1);
    [photoData writeToFile:filePath atomically:YES];
    
    0 讨论(0)
提交回复
热议问题