iPhone - UIImagePickerController -> save the image to app folder

后端 未结 4 873
刺人心
刺人心 2020-12-12 18:47

I have an iPhone application using a UIImagePickerController. As sourceType I have

  • UIImagePickerControllerSourceTypePhotoLibrary
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 19:04

    This is the code to save the UIImage into the document directory. You can use this code in didFinishPickingImage delegate method:

    // Create paths to output images
    NSString  *pngPath = [NSHomeDirectory();
    stringByAppendingPathComponent:@"Documents/Test.png"];
    NSString  *jpgPath = [NSHomeDirectory();
    stringByAppendingPathComponent:@"Documents/Test.jpg"];
    
    // Write a UIImage to JPEG with minimum compression (best quality)
    // The value 'image' must be a UIImage object
    // The value '1.0' represents image compression quality as value from 0.0 to 1.0
    [UIImageJPEGRepresentation(image, 1.0) writeToFile:jpgPath atomically:YES];
    
    // Write image to PNG
    [UIImagePNGRepresentation(image) writeToFile:pngPath atomically:YES];
    
    // Let's check to see if files were successfully written...
    
    // Create file manager
    NSError *error;
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    
    // Point to Document directory
    NSString *documentsDirectory = [NSHomeDirectory();
    stringByAppendingPathComponent:@"Documents"];
    
    // Write out the contents of home directory to console
    NSLog(@"Documents directory: %@", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);
    

    EDIT

    You can also use:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    

    to find the path to your application document directory, instead of NSHomeDierctory.

提交回复
热议问题