你可能知道如何呈現的圖像拾取:
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[viewController presentModalViewController:picker animated:YES];
隨着上述的viewController實現UIImagePickerControllerDelegate,並確保你實現這個功能:
- (void)imagePickerController:(UIImagePickerController *)returnedPicker didFinishPickingMediaWithInfo:(NSDictionary *)info
和
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)returnedPicker
第一種方法在用戶選擇照片時調用。在這種方法中你使用的圖像:
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
爲了寫這你可以把它一個JPEG或PNG文件。如果一個JPEG你可以這樣做:
[UIImageJPEGRepresentation(image, 1.0) writeToFile:filename atomically:YES];
你只需要設置文件名。
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [paths objectAtIndex:0];
NSString *filename = [docsDir stringByAppendingPathComponent:@"myFilename.jpg"];
要獲取圖像回一個UIImage你這樣做:
NSData *data = [NSData dataWithContentsOfFile:filename;
if(data != nil)
UIImage *image = [UIImage imageWithData:data];
非常感謝!這是非常具體的,所以文件名只是一個NSString?當我需要取回照片時,我還將文件名用作NSString,而不是像/ document/resource /或類似的東西考慮照片的文件路徑? – 2012-02-24 05:28:27
添加了幾行來解釋 - 是的,在這種情況下它只是一個NSString,但是您需要以文檔目錄爲前綴。 – Tonester 2012-02-24 09:16:27
再次感謝!這對我非常有幫助! – 2012-02-24 09:25:17