iPhone:如何在应用程序目录中将图像写入磁盘
Posted
技术标签:
【中文标题】iPhone:如何在应用程序目录中将图像写入磁盘【英文标题】:iPhone: How to Write an Image to Disk in the App Directories 【发布时间】:2010-03-04 14:52:54 【问题描述】:我正在做一个 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];
【问题讨论】:
你真的应该在你的计算机上而不是在 iPhone 环境中指定一个位置的路径吗? 【参考方案1】:您不应该有指向模拟器目录的硬编码路径。这将在设备上或模拟器重置时失败。除了应用程序的 Document 文件夹之外,您也不应该将用户数据保存在任何地方。
改为使用:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *pathToDocuments=[paths objectAtIndex:0];
这将返回应用程序的 Document 目录的当前路径,无论它在哪里运行或发生了什么变化。
您不应该在 iPhone 代码中使用绝对路径,因为系统会为了安全起见对路径进行打乱。始终根据需要使用动态检索路径的函数。
【讨论】:
以上是关于iPhone:如何在应用程序目录中将图像写入磁盘的主要内容,如果未能解决你的问题,请参考以下文章