How do I save a UIImage to a file?

前端 未结 9 897
抹茶落季
抹茶落季 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

    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 () 
    
    @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];
    

提交回复
热议问题