這個示例程序主要用到了IOS中的UIImageView、UIImagePickerViewController、UIImage、NSFileManager等知識,結合這些知識構成一個小的應用程序,主要功能是對相冊圖片進行讀取、存儲到指定文件夾、從指定文件夾讀取出來。這方面的知識在正式項目中用的是比較多的。做Android開發中,經常會使用到將圖片保存到SD卡和從SD卡讀取圖片的操作,相比於Android在這方面的操作,IOS要方便許多。
基本功能是從相冊選取一張圖片,選完后顯示在界面的UIImageView控件中,點擊保存到文件夾按鈕后就將圖片保存到Documents下的ImageFile文件夾中,以image.png命名。退出程序下次進來時,可以選擇從文件夾讀取圖片,如果有則讀取出來顯示在UIImageView上,如果沒有則提示文件不存在。
首先來看看最后效果:
·從相冊選取圖片后顯示在界面上
這里對功能進行了一點改進,點擊打開相冊按鈕后出來一個UIActionSheet操作選項框,可以選擇是從相機獲取圖片還是從相冊獲取。代碼也做出了一點修改。
·點擊保存到文件夾按鈕后提示信息
·點擊讀取圖片按鈕后的提示信息(圖片不存在)
·如果存在則將圖片顯示出來
保存圖片成功后,按照前一篇文章提到的方法,可以到Finder下查看文件信息:
下面是實現部分,首先看看布局文件:
下面是代碼:
- #import <UIKit/UIKit.h>
- @interface ViewController : UIViewController<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>
- @property (retain, nonatomic) IBOutlet UIImageView *imageView;
- @property (retain, nonatomic) UIButton *saveToFileButton;
- //打開相冊
- - (IBAction)openAlbum:(id)sender;
- //從文件夾讀取圖片
- - (IBAction)readImage:(id)sender;
- @end
下面是ViewController.m文件
- #import "ViewController.h"
- //保存到文件夾按鈕的標簽,選取圖片前,這個按鈕是隱藏的
- #define SAVE_BUTTON_TAG 101
- @interface ViewController ()
- @end
- @implementation ViewController
- @synthesize imageView = _imageView;
- @synthesize saveToFileButton = _saveToFileButton;
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- //根據設置的tag獲取按鈕控件
- self.saveToFileButton = (UIButton *)[self.view viewWithTag:SAVE_BUTTON_TAG];
- //添加對象事件
- [self.saveToFileButton addTarget:self action:@selector(saveToFileBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
- //設置為不可見
- self.saveToFileButton.hidden = YES;
- }
- - (void)viewDidUnload
- {
- [self setImageView:nil];
- [self setSaveToFileButton:nil];
- [super viewDidUnload];
- // Release any retained subviews of the main view.
- }
- - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
- {
- return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
- }
- - (void)dealloc {
- [self.imageView release];
- [self.saveToFileButton release];
- [super dealloc];
- }
- - (IBAction)openAlbum:(id)sender {
- UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"選擇圖片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相冊", nil];
- [actionSheet showInView:self.view];
- [actionSheet release];
- }
- //從文件夾讀取圖片
- - (IBAction)readImage:(id)sender {
- NSString *imagePath = [self imageSavedPath:@"image.png"];
- NSFileManager *fileManager = [NSFileManager defaultManager];
- //判斷文件是否存在
- if (![fileManager fileExistsAtPath:imagePath]) {
- UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Note" message:@"文件不存在" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
- [alertView show];
- [alertView release];
- }else {
- //從指定目錄讀取圖片
- UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
- self.imageView.image = image;
- }
- }
- //保存到文件按鈕事件
- - (void)saveToFileBtnTapped:(id)sender {
- NSString *imagePath = [self imageSavedPath:@"image.png"];
- BOOL isSaveSuccess = [self saveToDocument:self.imageView.image withFilePath:imagePath];
- if (isSaveSuccess) {
- UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"操作結果" message:@"保存圖片成功" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
- [alertView show];
- [alertView release];
- }else {
- UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"操作結果" message:@"保存圖片失敗" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
- [alertView show];
- [alertView release];
- }
- }
- //將選取的圖片保存到目錄文件夾下
- -(BOOL)saveToDocument:(UIImage *) image withFilePath:(NSString *) filePath
- {
- if ((image == nil) || (filePath == nil) || [filePath isEqualToString:@""]) {
- return NO;
- }
- @try {
- NSData *imageData = nil;
- //獲取文件擴展名
- NSString *extention = [filePath pathExtension];
- if ([extention isEqualToString:@"png"]) {
- //返回PNG格式的圖片數據
- imageData = UIImagePNGRepresentation(image);
- }else{
- //返回JPG格式的圖片數據,第二個參數為壓縮質量:0:best 1:lost
- imageData = UIImageJPEGRepresentation(image, 0);
- }
- if (imageData == nil || [imageData length] <= 0) {
- return NO;
- }
- //將圖片寫入指定路徑
- [imageData writeToFile:filePath atomically:YES];
- return YES;
- }
- @catch (NSException *exception) {
- NSLog(@"保存圖片失敗");
- }
- return NO;
- }
- //根據圖片名將圖片保存到ImageFile文件夾中
- -(NSString *)imageSavedPath:(NSString *) imageName
- {
- //獲取Documents文件夾目錄
- NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
- NSString *documentPath = [path objectAtIndex:0];
- //獲取文件管理器
- NSFileManager *fileManager = [NSFileManager defaultManager];
- //指定新建文件夾路徑
- NSString *imageDocPath = [documentPath stringByAppendingPathComponent:@"ImageFile"];
- //創建ImageFile文件夾
- [fileManager createDirectoryAtPath:imageDocPath withIntermediateDirectories:YES attributes:nil error:nil];
- //返回保存圖片的路徑(圖片保存在ImageFile文件夾下)
- NSString * imagePath = [imageDocPath stringByAppendingPathComponent:imageName];
- return imagePath;
- }
- #pragma Delegate method UIImagePickerControllerDelegate
- //圖像選取器的委托方法,選完圖片后回調該方法
- -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
- {
- if (image != nil) {
- //選定照片后在界面顯示照片並把保存按鈕設為可見
- self.imageView.image = image;
- self.saveToFileButton.hidden = NO;
- }
- //關閉圖像選擇器
- [self dismissModalViewControllerAnimated:YES];
- }
- -(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
- {
- //獲取圖片選取器
- UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
- //指定代理
- imagePicker.delegate = self;
- //打開圖片后允許編輯
- imagePicker.allowsEditing = YES;
- //判斷圖片源的類型
- if (buttonIndex == 0) {
- if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
- //相機
- imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
- }
- }else if (buttonIndex == 1) {
- if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
- //圖片庫
- imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
- }
- // if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
- // //相冊
- // imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
- // }
- }else if (buttonIndex == [actionSheet cancelButtonIndex]) {
- return;
- }
- //打開圖片選擇模態視圖
- [self presentModalViewController:imagePicker animated:YES];
- [imagePicker release];
- }
- @end