iOS拍照 相册选取 保存PNG图片到Documents下,并利用UICollectionView显示出来

最近闲来无事,研究了一下拍照保存并利用UICollectionView显示出来 ,保存的同时会存一份缩略图到Documents的thumb文件夹下,UIColletionView显示先调去缩略图

AppDelegate.m就不写了,定义一个UINavigationViewController

ViewController.h

拖三个按钮到nib,分别是拍照,相册选取,查看照片,并连接输出


//
//  ViewController.h
//  sendphoto
//
//  Created by eastime on 13-11-27.
//  Copyright (c) 2013年 com.eastime. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
  //  UIImage *_image;
   
    
    UIImagePickerController *imagePicker;
}
@property (retain, nonatomic) IBOutlet UIButton *pickPhoto;

@property (retain, nonatomic) IBOutlet UIButton *takePhoto;

@property (retain, nonatomic) IBOutlet UIButton *viewPhoto;

- (IBAction)takePhoto:(id)sender;
- (IBAction)pickPhoto:(id)sender;
- (IBAction)viewPhoto:(id)sender;

@end


ViewController.m

//
//  ViewController.m
//  sendphoto
//
//  Created by eastime on 13-11-27.
//  Copyright (c) 2013年 com.eastime. All rights reserved.
//

#import "ViewController.h"
#import "gridViewController.h"

@interface ViewController ()

@end

@implementation ViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self creatFileAndWriteDataTOFile];
    // Do any additional setup after loading the view from its nib.
}


#pragma mark 判断thumb目录存在与否,不存在进行创建
- (NSString *) dataPath{
    NSArray *storeFilePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *doucumentsDirectiory = [storeFilePath objectAtIndex:0];
    return [doucumentsDirectiory stringByAppendingPathComponent:[NSString stringWithFormat:@"/thumb"]];
}
-(void)creatFileAndWriteDataTOFile {
    //判断目录是否存在
    if(![[NSFileManager defaultManager] isExecutableFileAtPath:[self dataPath]]) {
        NSLog(@"create");
        //创建目录
        [[NSFileManager defaultManager] createDirectoryAtPath:[self dataPath]withIntermediateDirectories:YES attributes:nil error:nil];
    }
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [_pickPhoto release];
    [_takePhoto release];
    
    [_viewPhoto release];
    [super dealloc];
}
- (IBAction)takePhoto:(id)sender {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    //判断是否有摄像头
    if(![UIImagePickerController isSourceTypeAvailable:sourceType])
    {
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;   // 设置委托
    imagePickerController.sourceType = sourceType;
    imagePickerController.allowsEditing = NO;
    [self presentViewController:imagePickerController animated:YES completion:nil];  //需要以模态的形式展示
    [imagePickerController release];
}




#pragma mark -
#pragma mark UIImagePickerController Method
//完成拍照
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    UIImage *image=[info objectForKey:@"UIImagePickerControllerOriginalImage"];
    
    UIImage *smallImg=[self scaleImage:image toScale:0.3];
  
    
    UIImageView *imgView=[[UIImageView alloc]initWithImage:image];
    imgView.frame=CGRectMake(20.0, 20.0, 280.0, 210.0);
    [self.view addSubview:imgView];
    
    NSString *tmpuuid=[self uuid];
    NSString *uuidpng=[NSString stringWithFormat:@"%@.png",tmpuuid];
    [self saveImage:image WithName:uuidpng];
    [self saveSmallImg:smallImg WithName:uuidpng];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    
}
//用户取消拍照

-(NSString*) uuid {
    CFUUIDRef puuid = CFUUIDCreate( nil );
    CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
    NSString * result = (NSString *)CFStringCreateCopy( NULL, uuidString);
    CFRelease(puuid);
    CFRelease(uuidString);
    return [result autorelease];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark 保存图片到document
- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName
{
    NSData* imageData = UIImagePNGRepresentation(tempImage);
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory = [paths objectAtIndex:0];
    // Now we get the full path to the file
    NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
    // and then we write it out
    [imageData writeToFile:fullPathToFile atomically:NO];
}


#pragma mark 保存图片到document\thumb
- (void)saveSmallImg:(UIImage *)tempImage WithName:(NSString *)imageName
{
    NSData* imageData = UIImagePNGRepresentation(tempImage);
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory = [paths objectAtIndex:0];
    NSString *docDirThumb=[NSString stringWithFormat:@"%@/thumb",documentsDirectory];
    // Now we get the full path to the file
    NSString* fullPathToFile = [docDirThumb stringByAppendingPathComponent:imageName];
    // and then we write it out
    [imageData writeToFile:fullPathToFile atomically:NO];
}


#pragma mark 从文档目录下获取Documents路径
- (NSString *)documentFolderPath
{
    return [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
}

#pragma mark 压缩照片
-(UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}


- (IBAction)pickPhoto:(id)sender {
    imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePicker.allowsEditing = NO;
    
    [self presentViewController:imagePicker animated:YES completion:nil];
}

- (IBAction)viewPhoto:(id)sender {
    gridViewController *gridView=[[gridViewController alloc]initWithNibName:@"gridViewController" bundle:nil];
    [self.navigationController pushViewController:gridView animated:YES];
    
}
@end


接着新建一个view,光view,取名例如CustomCell,新建完成以后把里面的view删掉,从右边控件栏拖一个Collection View Cell到中间,定义好这个Cell的大小,然后从右边控件栏拖一个UIImageView和一个Label到这个Cell View里,分别设置他们的tag属性,比如一个1,一个2





完成以后新建一个类比如gridViewController,继承自UICollecionViewController


新建完成后删除原来的view,从右边控件栏拖一个CollectionView到中间,做好连接



gridViewController.h

//
//  gridViewController.h
//  sendphoto
//
//  Created by eastime on 13-12-3.
//  Copyright (c) 2013年 com.eastime. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface gridViewController : UICollectionViewController
{
    NSMutableArray *_items;
}

@end

gridViewController.m

//
//  gridViewController.m
//  sendphoto
//
//  Created by eastime on 13-12-3.
//  Copyright (c) 2013年 com.eastime. All rights reserved.
//

#import "gridViewController.h"

@interface gridViewController ()

@end

@implementation gridViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _items=[[NSMutableArray alloc]init];
    
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSArray* filename = [self getFilenamelistOfType:@"png" fromDirPath:path];
    NSArray *sortedArray;
    sortedArray = [filename sortedArrayUsingFunction:intSort context:NULL];
    
    
    for (int i=0; i<[sortedArray count]; i++) {
        NSLog(@"%@",[sortedArray objectAtIndex:i]);
        NSString *tp=[NSString stringWithFormat:@"%d",i];
        NSMutableDictionary *dic=[NSMutableDictionary dictionary];
        [dic setObject:[sortedArray objectAtIndex:i] forKey:tp];
        [_items addObject:dic];
    }
    
    
    UINib *cellNib=[UINib nibWithNibName:@"CustomCell" bundle:nil];
    [self.collectionView registerNib:cellNib forCellWithReuseIdentifier:@"Cell"];
    
    // Do any additional setup after loading the view from its nib.
}





int intSort(id string2, id string1, void *locale)

{
    
    static NSStringCompareOptions comparisonOptions =
    NSCaseInsensitiveSearch | NSNumericSearch |
    NSWidthInsensitiveSearch | NSForcedOrderingSearch;
    NSRange string1Range = NSMakeRange(0, [string1 length]);
    return [string1 compare:string2 options:comparisonOptions range:string1Range locale:(NSLocale *)locale];
    
}

-(NSArray *) getFilenamelistOfType:(NSString *)type fromDirPath:(NSString *)dirPath

{
    
    NSArray *fileList = [[[NSFileManager defaultManager] contentsOfDirectoryAtPath:dirPath error:nil] pathsMatchingExtensions:[NSArray arrayWithObject:type]];
    
    return fileList;
    
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [_items count];
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier=@"Cell";
    
    NSString *titleContent=[NSString stringWithFormat:@"%d",indexPath.row+1];
    
    NSLog(@"%@",titleContent);
    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    
    NSDictionary *dic=[_items objectAtIndex:indexPath.row];
    NSString *t=[NSString stringWithFormat:@"%d",indexPath.row];
    

    NSString *filename=[NSString stringWithFormat:@"%@",[dic objectForKey:t]];
    
    
    
    //定位到Documents目录
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    NSString *thumbDir=[NSString stringWithFormat:@"%@/thumb",docDir];
    NSString *filePath = [thumbDir stringByAppendingPathComponent:filename];
 
    NSLog(@"%@",filePath);
    
    
    UIImage *img = [UIImage imageWithContentsOfFile:filePath];
    UIImageView *imgView=(UIImageView *)[cell viewWithTag:1];
    
    [imgView setImage:img];
    
    
    UILabel *titlelabel=(UILabel *)[cell viewWithTag:2];
    titlelabel.text=titleContent;
    return cell;
}





- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值