最好的方法是在您收到图像后立即将图像保存在应用程序的文件夹中。
这很重要,因为它有助于内存管理。
您可以放开图像数据,而不是在应用程序中传递它。
我使用类似于以下的代码:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *originalImage, *editedImage, *imageToSave;
editedImage = (UIImage *) [info objectForKey:
UIImagePickerControllerEditedImage];
originalImage = (UIImage *) [info objectForKey:
UIImagePickerControllerOriginalImage];
imageToSave = (editedImage!=nil ? editedImage : originalImage);
// Check if the image was captured from the camera
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
// Save the image to the camera roll
UIImageWriteToSavedPhotosAlbum(imageToSave, nil, nil, nil);
}
NSString *docspath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filepathJPG = [docspath stringByAppendingPathComponent:@"imagefile.jpg"];
NSData *data = UIImageJPEGRepresentation(imageToSave, 0.8);
BOOL result = [data writeToFile:filepathJPG atomically:YES];
NSLog(@"Saved to %@? %@", filepathJPG, (result? @"YES": @"NO") );
[picker dismissModalViewControllerAnimated:YES];
}
然后在您的其他视图控制器中,无论您希望加载图像(viewDidLoad、viewWillAppear 还是其他任何地方),都放:
NSString *docspath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filepathJPG = [docspath stringByAppendingPathComponent:@"imagefile.jpg"];
UIImage *img = [UIImage imageWithContentsOfFile: filepathJPG];
if (img != nil) {
// assign the image to the imageview,
myImageView.image = img;
// Optionally adjust the size
BOOL adjustToSmallSize = YES;
CGRect smallSize = (CGRect){0,0,100,100};
if (adjustToSmallSize) {
myImageView.bounds = smallSize;
}
}
else {
NSLog(@"Image hasn't been created");
}
希望有帮助