如何在iPhone上加载图像

时间:2010-12-28 22:34:25

标签: iphone cocoa-touch

我正在使用UIImagePickerController,一旦选择了图像,我将其保存为PNG。但由于某种原因,我无法加载保存的图像。

这是我的代码:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    //
// Create a PNG representation of the edited image
//
UIImage *anImage   = [info valueForKey:UIImagePickerControllerEditedImage];
NSData  *imageData = UIImagePNGRepresentation(anImage);

//
// Save the image to the documents directory
//
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

// Get a unique filename for the file
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
NSString *fileName = [(NSString *)string autorelease];
fileName = [NSString stringWithFormat:@"images/%@", fileName];
fileName = [fileName stringByAppendingString:@".png"];

NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithString:fileName] ];
[imageData writeToFile:path atomically:YES];
NSLog(@"Wrote the imageData to a file at path: %@", path);

// TEST TO SEE IF THE FILE WAS WRITTEN CORRECTLY
UIImage *testImage = [UIImage imageWithContentsOfFile:path];
NSLog(@"testImage is %@", testImage);

这是我的调试器输出:

2010-12-28 16:29:08.676 Appster[6656:207] The imagePath is defined as: images/7ADB104E-DA45-4EE9-88DA-FF71B8D730CA.png
2010-12-28 16:29:08.712 Appster[6656:207] Wrote the imageData to a file at path: /Users/bschiff/Library/Application Support/iPhone Simulator/4.2/Applications/9F6FC2C7-9369-438C-AF8F-D5D25C72D8D7/Documents/images/FC94AA93-02EC-492A-A8FE-7D0C76E2C085.png
2010-12-28 16:29:08.715 Appster[6656:207] testImage is (null)

1 个答案:

答案 0 :(得分:0)

您是否尝试过使用NSBundle来引用资源路径?

试试这个:

[[NSBundle mainBundle] pathForResource:[NSString stringWithString:fileName] 
                                ofType:@"png" inDirectory:@"images"]]

使用该路径保存和检索图像文件