iPhone:如何在应用程序目录中将图像写入磁盘

问题描述:

我正在开发一个iPhone项目,其中需要将相机图像保存到磁盘和文件,但以下代码失败: (******** ****iPhone:如何在应用程序目录中将图像写入磁盘

-(void)imagePickerController:(UIImagePickerController *) picker didFinishPickingMediaWithInfo:(NSDictionary *)info { 

[picker dismissModalViewControllerAnimated:YES]; 
imageView.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"]; 
imgglobal =imageView.image; 
NSString *newFilePath = [NSHomeDirectory() stringByAppendingPathComponent: @"~/Users/abc/Library/Application Support/iPhone Simulator/User/Applications/SAVE_IMAGE_TEST1.JPG"]; 
NSData *imageData = UIImageJPEGRepresentation(imageView.image, 1.0); 
NSData *data = imageData; 
if (imageData != nil) { 
    [imageData writeToFile:newFilePath atomically:YES]; 
} 
if ([[NSFileManager defaultManager] createFileAtPath:@"~/Users/abc/Library/Application Support/iPhone Simulator/User/Applications/SAVE_IMAGE_TEST1.JPG" contents:data attributes:nil]) 
{ 
    UIAlertView *successAlert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Image was successfully saved to the Photo Library." delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil]; 
    [successAlert show]; 
    [successAlert release]; 
} else { 
    UIAlertView  *failureAlert = [[UIAlertView alloc] initWithTitle:@"Failure" message:@"Failed to save image to the Photo Library." delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil]; 
    [failureAlert show]; 
    [failureAlert release]; 
}  
} 
+1

您是否真的应该在计算机上指定路径而不是在iPhone环境中? – willcodejavaforfood 2010-03-04 14:58:01

你不应该到模拟器目录的硬编码路径,这将在设备或在模拟器上复位失败,你也不应该保存用户数据的任何地方,但应用程序的文件夹。

而是使用:

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

这将返回应用程序的Document目录的当前路径,而不管它在哪里运行或发生了什么变化。

您不应该在iPhone代码中使用绝对路径,因为系统会对路径进行加扰以提高安全性。始终使用根据需要动态检索路径的函数。