這個示例程式主要用到了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
中間有些操作過程我就沒有一一例舉了,比如如何将控件與代碼關聯,如何設定控件的TAG等。需要代碼的朋友可以給我留言,我發你們郵箱!
加入我們的QQ群或微信公衆賬号請檢視: Ryan's zone公衆賬号及QQ群
歡迎關注我的新浪微網誌和我交流:@唐韌_Ryan