iOS 拍照以及從相簿取出照片
最近在開發camera and album 相關功能的app。將一些用法以及代碼筆記下來。
LCSViewController.h and LCSViewController.m
#import@interface LCSViewController:UIViewController @property(nonatomic,retain)IBOutlet UIImageView *imageView; @property(nonatomic,retain)IBOutlet UIBarButtonItem *saveImageBotton; -(IBAction)showCameraAction:(id)sender;//拍照 -(IBAction)saveImageAction:(id)sender;//將照片存到相簿 -(IBAction)pickPhotoFromLibery:(id)sender;//從相簿取出照片 @end
#import "LCSViewController.h"
@interface LCSViewController ()
@end
@implementation LCSViewController
@synthesize imageView;
@synthesize saveImageBotton;
#pragma mark - Show camera
-(IBAction)showCameraAction:(id)sender
{
UIImagePickerController *imagePickController=[[UIImagePickerController alloc]init];
//You can use isSourceTypeAvailable to check
imagePickController.sourceType=UIImagePickerControllerSourceTypeCamera;
imagePickController.delegate=self;
imagePickController.allowsEditing=YES;
imagePickController.showsCameraControls=YES;
//This method inherit from UIView,show imagePicker with animation
[self presentModalViewController:imagePickController animated:YES];
[imagePickController release];
}
#pragma mark - Show Album
-(IBAction)pickPhotoFromLibery:(id)sender{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
picker.allowsEditing = YES;
[self presentModalViewController:picker animated:YES];
[picker release];
}
#pragma mark - When Tap Save Button
-(IBAction)saveImageAction:(id)sender
{
UIImage *image=imageView.image;
//save photo to photoAlbum
UIImageWriteToSavedPhotosAlbum(image,self, @selector(CheckedImage:didFinishSavingWithError:contextInfo:), nil);
saveImageBotton.enabled=NO;
NSLog(@"save image");
}
#pragma mark - Check Save Image Error
- (void)CheckedImage:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
UIAlertView *alert;
if (error) {
alert = [[UIAlertView alloc] initWithTitle:@"錯誤"
message:[error description]
delegate:self
cancelButtonTitle:@"確定"
otherButtonTitles:nil];
} else {
alert = [[UIAlertView alloc] initWithTitle:@"成功"
message:@"照片已經存到相簿"
delegate:self
cancelButtonTitle:@"確定"
otherButtonTitles:nil];
}
[alert show];
[alert release];
}
#pragma mark - When Finish Shoot
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *originalImage=[info objectForKey:UIImagePickerControllerOriginalImage];
//Show OriginalImage size
imageView.image=originalImage;
saveImageBotton.enabled=YES;
[self dismissModalViewControllerAnimated:YES];
}
#pragma mark - When Tap Cancel
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissModalViewControllerAnimated:YES];
}
#pragma mark - Release object
- (void)dealloc {
[imageView release];
[saveImageBotton release];
[super dealloc];
}
留言
張貼留言