Proper way of saving and loading pictures

前端 未结 3 1472
说谎
说谎 2021-02-04 13:41

I am making a small app where the user can create a game profile, input some data and a picture that can be taken with the camera.

I save most of that profile data with

3条回答
  •  深忆病人
    2021-02-04 14:36

    You should save it in Documents or Cache folder. Here is how to do it.

    Saving into Documents folder:

    NSString* path = [NSHomeDirectory() stringByAppendingString:@"/Documents/myImage.png"];
    
    BOOL ok = [[NSFileManager defaultManager] createFileAtPath:path 
              contents:nil attributes:nil];
    
    if (!ok) 
    {
        NSLog(@"Error creating file %@", path);
    } 
    else 
    {
        NSFileHandle* myFileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
       [myFileHandle writeData:UIImagePNGRepresentation(yourImage)];
       [myFileHandle closeFile];
    }
    

    Loading from Documents folder:

    NSFileHandle* myFileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
    UIImage* loadedImage = [UIImage imageWithData:[myFileHandle readDataToEndOfFile]];
    

    You can also use UIImageJPEGRepresentation to save your UIImage as a JPEG file. What's more if you want to save it in Cache directory, use:

    [NSHomeDirectory() stringByAppendingString:@"/Library/Caches/"]
    

提交回复
热议问题