iOS 保存多张bundle里面的图片到相册

//
//  EncodeViewController.m
//  demoGifLib
//
//  Created by soleilpqd on 10/28/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "EncodeViewController.h"
#import <giflib/GifEncode.h>
#import <giflib/giflib_ios.h>
#import <AssetsLibrary/AssetsLibrary.h>

@interface EncodeViewController() {
    NSArray *_items;
    UIView *_vwLock;
    UIActivityIndicatorView *_indicator;
    
    ALAssetsLibrary *_assetsLibrary;
}

@property(nonatomic, strong)NSMutableArray *listImages;
@property(nonatomic, strong)NSArray *items;

- ( void )showLockView;
- ( void )dismissLockView;

@end

@implementation EncodeViewController

- ( void )showLockView {
    if ( _vwLock == nil ) {
        _vwLock = [[ UIView alloc ] initWithFrame:self.view.bounds ];
        _indicator = [[ UIActivityIndicatorView alloc ] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge ];
        _vwLock.backgroundColor = [[ UIColor blackColor ] colorWithAlphaComponent:0.5 ];
        _indicator.center = CGPointMake( _vwLock.bounds.size.width / 2, _vwLock.bounds.size.height / 2 );
        [ _vwLock addSubview:_indicator ];
    }
    [ self.view addSubview:_vwLock ];
    [ _indicator startAnimating ];
}

- ( void )dismissLockView {
    [ _vwLock removeFromSuperview ];
    [ _indicator stopAnimating ];
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    _items = [[ NSFileManager defaultManager ] contentsOfDirectoryAtPath:[[[ NSBundle mainBundle ] bundlePath ] stringByAppendingPathComponent:@"frames" ]
                                                                    error:NULL ];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return UIInterfaceOrientationIsPortrait( interfaceOrientation );
}

- ( void )dealloc {
//    [ _items release ];
//    if ( _vwLock ) {
//        [ _vwLock release ];
//        [ _indicator release ];
//    }
//    [ super dealloc ];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    NSString *s = [ _items objectAtIndex:indexPath.row ];
    cell.textLabel.text = s.stringByDeletingPathExtension;
    NSBundle *bundle = [ NSBundle bundleWithPath:[[[ NSBundle mainBundle ] bundlePath ] stringByAppendingFormat:@"/frames/%@", s ]];
    cell.imageView.image = [ UIImage imageWithContentsOfFile:[ bundle pathForResource:@"0" ofType:@"png" ]];
    
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [ tableView deselectRowAtIndexPath:indexPath animated:YES ];
    NSString *s = [ _items objectAtIndex:indexPath.row ];
    NSBundle *bundle = [ NSBundle bundleWithPath:[[[ NSBundle mainBundle ] bundlePath ] stringByAppendingFormat:@"/frames/%@", s ]];
    NSArray *arr = [[ NSFileManager defaultManager ] contentsOfDirectoryAtPath:bundle.bundlePath
                                                                         error:NULL ];
    UIAlertView *alert = [[ UIAlertView alloc ] initWithTitle:@"Encode confirm"
                                                      message:[ NSString stringWithFormat:@"Encode %i frames of \"%@\"?", arr.count, s.stringByDeletingPathExtension ]
                                                     delegate:self
                                            cancelButtonTitle:@"Cancel"
                                            otherButtonTitles:@"OK", nil ];
    alert.tag = indexPath.row;
    [ alert show ];
//    [ alert release ];
}

- ( void )alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if ( buttonIndex ) {
        [ self showLockView ];
        [ self performSelectorInBackground:@selector( startEncodeWithBundleName: )
                                withObject:[ _items objectAtIndex:alertView.tag ]];
    }
}

- (NSArray *)findGIFImageInNormal:(NSString *)gifName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *documentsDirectory = [paths objectAtIndex:0];
    //    NSString *strFile = [documentsDirectory stringByAppendingPathComponent:@"hello/config.plist"];
    //    NSLog(@"strFile: %@", strFile);
    
    NSString *strPath = [documentsDirectory stringByAppendingPathComponent:@"Normal"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:strPath]) {
        NSLog(@"there is no Directory: %@",strPath);
        //        [[NSFileManager defaultManager] createDirectoryAtPath:strPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    //取得当前目录下的全部文件
    //    NSFileManager *fileManage = [NSFileManager defaultManager];
    //    NSArray *file = [fileManage subpathsOfDirectoryAtPath:strPath error:nil];
    //    NSArray *file = [self getFilenamelistOfType:@"png" fromDirPath:strPath];
    NSArray *file = [self getFilenamelistOfType:@"png" fromDirPath:strPath GIFName:gifName];
    //    NSLog(@"the file is %@", file);
    return file;
    
}

-(NSArray *) getFilenamelistOfType:(NSString *)type fromDirPath:(NSString *)dirPath GIFName:(NSString *)gifName
{
    NSArray *tempList = [[[NSFileManager defaultManager] contentsOfDirectoryAtPath:dirPath error:nil]
                         pathsMatchingExtensions:[NSArray arrayWithObject:type]];
    NSMutableArray *fileList = [NSMutableArray array];
    for (NSString *fileName in tempList) {
        //       NSString *name = [[fileName componentsSeparatedByString:@"."] objectAtIndex:0];
        //        if ([fileName isEqualToString:gifName] ) {
                    [fileList removeObject:fileName];
        //            [fileList addObject:fileName];
        //        }
        if ([fileName rangeOfString:gifName].location != NSNotFound) {
            //        if ([fileName rangeOfString:gifName] ) {
            //            [fileList removeObject:fileName];
            [fileList addObject:fileName];
        }
        
        //        NSLog(@"fileName is %@", name);
    }
    tempList = nil;
    
    //    //block比较方法,数组中可以是NSInteger,NSString(需要转换)
    //    NSComparator finderSort = ^(id string1,id string2){
    //
    //        if ([string1 integerValue] > [string2 integerValue]) {
    //            return (NSComparisonResult)NSOrderedDescending;
    //        }else if ([string1 integerValue] < [string2 integerValue]){
    //            return (NSComparisonResult)NSOrderedAscending;
    //        }
    //        else
    //            return (NSComparisonResult)NSOrderedSame;
    //    };
    //
    //    //数组排序:
    //    NSArray *resultArray = [fileList sortedArrayUsingComparator:finderSort];
    //    NSLog(@"第一种排序结果:%@",resultArray);
    
    NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch|NSNumericSearch|
    NSWidthInsensitiveSearch|NSForcedOrderingSearch;
    NSComparator sort = ^(NSString *obj1,NSString *obj2){
        NSRange range = NSMakeRange(0,obj1.length);
        return [obj1 compare:obj2 options:comparisonOptions range:range];
    };
    NSArray *resultArray2 = [fileList sortedArrayUsingComparator:sort];
    //    NSLog(@"字符串数组排序结果%@",resultArray2);
    
    
    return resultArray2;
    //    return fileList;
}

- ( void )startEncodeWithBundleName:( NSString* )bundleName {
//    NSAutoreleasePool *pool = [[ NSAutoreleasePool alloc ] init ];
    NSFileManager *fileMan = [ NSFileManager defaultManager ];
    NSBundle *bundle = [ NSBundle bundleWithPath:[[[ NSBundle mainBundle ] bundlePath ] stringByAppendingFormat:@"/frames/%@", bundleName ]];
    
    NSString *testImageName = @"joy";
    NSString *bundleName1 = @"joy.bundle";
    NSBundle *bundle1 = [ NSBundle bundleWithPath:[[[ NSBundle mainBundle ] bundlePath ] stringByAppendingFormat:@"/frames/%@", bundleName1 ]];
    
    NSMutableArray *arrayImage = [NSMutableArray array];
    
    NSArray *fileList = [self findGIFImageInNormal:@"tset"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    
    NSString *imageDirectory = [path stringByAppendingPathComponent:@"Normal"];
    
    for (NSString *iamgeName in fileList) {
        NSString *fileURL =[imageDirectory stringByAppendingPathComponent:iamgeName];
//        [UIImage imageWithContentsOfFile:fileURL]
        [arrayImage addObject:[UIImage imageWithContentsOfFile:fileURL]];
    }
    
//    NSString *stt = @"232323";
//    NSString *test = stt.copy;
    NSString *gifName = [bundleName stringByDeletingPathExtension].copy;
    NSString *resourceName = [NSString stringWithFormat:@"%@0", gifName].copy;
    UIImage *image = [ UIImage imageWithContentsOfFile:[ bundle pathForResource:resourceName
                                                                         ofType:@"png" ]];
    NSLog(@"the length is %f", image.size.width);
    NSLog(@"the length is %f", image.size.height);
    GifEncode *encoder = [[ GifEncode alloc ] initWithFile:[ NSHomeDirectory() stringByAppendingString:@"/Library/Caches/temp.gif" ]
                                                targetSize:image.size
                                                 loopCount:0
                                                  optimize:NO ];
    if ( encoder.error == 0 ) {
        NSLog( @"Encode frame 0" );
        [ encoder putImageAsFrame:image
                      frameBounds:CGRectMake( 0, 0, image.size.width, image.size.height )
                        delayTime:0.1
                     disposalMode:DISPOSE_DO_NOT
                   alphaThreshold:0.5 ];
        if ( encoder.error != 0 ) {
            [ self showError:encoder.error ];
//            [ encoder release ];
//            [ pool release ];
            return;
        }
        
//        NSString *resourceName1 = [NSString stringWithFormat:@"%@1", gifName].copy;
//        UIImage *image1 = [ UIImage imageWithContentsOfFile:[ bundle pathForResource:resourceName1
//                                                                             ofType:@"png" ]];
//        [ encoder putImageAsFrame:image1
//                      frameBounds:CGRectMake( 0, 0, image1.size.width, image1.size.height )
//                        delayTime:0.1
//                     disposalMode:DISPOSE_DO_NOT
//                   alphaThreshold:0.5 ];
//        
//        NSString *resourceName2 = [NSString stringWithFormat:@"%@2", gifName].copy;
//        UIImage *image2 = [ UIImage imageWithContentsOfFile:[ bundle pathForResource:resourceName2
//                                                                              ofType:@"png" ]];
//        [ encoder putImageAsFrame:image2
//                      frameBounds:CGRectMake( 0, 0, image2.size.width, image2.size.height )
//                        delayTime:0.1
//                     disposalMode:DISPOSE_DO_NOT
//                   alphaThreshold:0.5 ];
        
        
        NSArray *arr = [ fileMan contentsOfDirectoryAtPath:bundle.bundlePath
                                                     error:NULL ];
        
//        for ( int i = 1; i < arr.count; i++ ) {
//            NSLog( @"Encode frame %i", i );
//            
//            NSLog(@"%@", [ NSString stringWithFormat:@"%@%i",gifName, i] );
//            
//            image = [ UIImage imageWithContentsOfFile:[ bundle pathForResource:[ NSString stringWithFormat:@"%@%i",gifName, i]
//                                                                        ofType:@"png" ]];
//            NSLog(@"the length is %f", image.size.width);
//            NSLog(@"the length is %f", image.size.height);
//            
//            [ encoder putImageAsFrame:image
//                          frameBounds:CGRectMake( 0, 0, image.size.width, image.size.height )
//                            delayTime:0.1
//                         disposalMode:DISPOSE_DO_NOT
//                       alphaThreshold:0.5 ];
//            if ( encoder.error != 0 ) {
//                [ self showError:encoder.error ];
                [ encoder release ];
                [ pool release ];
//                return;
//            }
//        }
//    [ encoder close ];
        
        UIImage *imagePoint;
        _listImages = [NSMutableArray array];
        for ( int i = 0; i < arr.count; i++ ) {
            NSLog( @"Encode frame %i", i );
            
            NSLog(@"%@", [ NSString stringWithFormat:@"%@%i",gifName, i] );
            
            imagePoint = [ UIImage imageWithContentsOfFile:[ bundle pathForResource:[ NSString stringWithFormat:@"%@%i",gifName, i]
                                                                        ofType:@"png" ]];
            [_listImages addObject:imagePoint];
            
            
//            GifEncode *encoder = [[ GifEncode alloc ] initWithFile:[ NSHomeDirectory() stringByAppendingString:@"/Library/Caches/temp.gif" ]
//                                                        targetSize:image.size
//                                                         loopCount:0
//                                                          optimize:NO ];
//            if ( encoder.error == 0 ) {
//                NSLog( @"Encode frame 0" );
//                [ encoder putImageAsFrame:image
//                              frameBounds:CGRectMake( 0, 0, image.size.width, image.size.height )
//                                delayTime:0.1
//                             disposalMode:DISPOSE_DO_NOT
//                           alphaThreshold:0.5 ];
//                if ( encoder.error != 0 ) {
//                    [ self showError:encoder.error ];
//                    //            [ encoder release ];
//                    //            [ pool release ];
//                    return;
//                }
            
//            NSLog(@"the length is %f", image.size.width);
//            NSLog(@"the length is %f", image.size.height);
//            
//            [ encoder putImageAsFrame:image
//                          frameBounds:CGRectMake( 0, 0, image.size.width, image.size.height )
//                            delayTime:0.1
//                         disposalMode:DISPOSE_DO_NOT
//                       alphaThreshold:0.5 ];
//            if ( encoder.error != 0 ) {
//                [ self showError:encoder.error ];
//                //                [ encoder release ];
//                //                [ pool release ];
//                return;
//            }
        }
//        [ encoder close ];

        
//        _listImages = [arr mutableCopy];
        
        NSLog(@"listimage count is %lu", (unsigned long)_listImages.count);
            
        
        _assetsLibrary = [ALAssetsLibrary new];
        
        [self saveNext];
        
//    UIImage *image1 = arrayImage[0];
//    NSLog(@"the size is %@", NSStringFromCGSize(image1.size));
//    NSLog(@"the size is %f", image1.size.height);
//    NSLog(@"the size is %f", image1.size.width);
    image1.size
//    GifEncode *encoder = [[ GifEncode alloc ] initWithFile:[ NSHomeDirectory() stringByAppendingString:@"/Library/Caches/temp.gif" ]
//                                                targetSize:image1.size
//                                                 loopCount:0
//                                                  optimize:YES ];
//    if ( encoder.error == 0 ) {
//        NSLog( @"Encode frame 0" );
//        [ encoder putImageAsFrame:arrayImage[0]
//                      frameBounds:CGRectMake( 0, 0, image1.size.width, image1.size.height )
//                        delayTime:0.03f
//                     disposalMode:DISPOSE_DO_NOT
//                   alphaThreshold:0.5 ];
//        if ( encoder.error != 0 ) {
//            [ self showError:encoder.error ];
//            [ encoder release ];
//            [ pool release ];
//            return;
//        }
//        NSArray *arr = [ fileMan contentsOfDirectoryAtPath:bundle.bundlePath
//                                                     error:NULL ];
        for ( int i = 1; i < arr.count; i++ ) {
            NSLog( @"Encode frame %i", i );
            image = [ UIImage imageWithContentsOfFile:[ bundle pathForResource:[ NSString stringWithFormat:@"joy%i", i ]
                                                                                 ofType:@"png" ]];
            [ encoder putImageAsFrame:image
                          frameBounds:CGRectMake( 0, 0, image.size.width, image.size.height )
                            delayTime:0.1
                         disposalMode:DISPOSE_DO_NOT
                       alphaThreshold:0.5 ];
            if ( encoder.error != 0 ) {
                [ self showError:encoder.error ];
                [ encoder release ];
                [ pool release ];
                return;
            }
        } fileList.count
//        
//        for ( int i = 1; i < 19; i++ ) {
//            NSLog( @"Encode frame %i", i );
            image = [ UIImage imageWithContentsOfFile:[ bundle pathForResource:[ NSString stringWithFormat:@"joy%i", i ]
                                                                        ofType:@"png" ]];
//            [ encoder putImageAsFrame:arrayImage[i]
//                          frameBounds:CGRectMake( 0, 0, image1.size.width, image1.size.height )
//                            delayTime:0.03f
//                         disposalMode:DISPOSE_DO_NOT
//                       alphaThreshold:0.5 ];
//            if ( encoder.error != 0 ) {
//                [ self showError:encoder.error ];
//                [ encoder release ];
//                [ pool release ];
//                return;
//            }
//        }


        
#if 0 //for test image saved
//        [ encoder close ];
        NSString *lastPath = [ NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@.gif", bundleName.stringByDeletingPathExtension ];
        if ([ fileMan fileExistsAtPath:lastPath ]) [ fileMan removeItemAtPath:lastPath error:NULL ];
        [ fileMan moveItemAtPath:encoder.gifFile
                          toPath:lastPath
                           error:NULL ];
//        [ encoder release ];
        [ self performSelectorOnMainThread:@selector( dismissLockView )
                                withObject:nil
                             waitUntilDone:NO ];
#endif
        
    }

    else {
        [ self showError:encoder.error ];
//        [ encoder release ];
    }
//    [ pool release ];
//#endif
}

-(void) saveNext{
    if (_listImages.count > 0) {
        UIImage *image = [_listImages objectAtIndex:0];
        //        UIImageWriteToSavedPhotosAlbum(image, self, @selector(savedPhotoImage:didFinishSavingWithError:contextInfo:), nil);
        NSLog(@"the remain image count is %lu", (unsigned long)_listImages.count);
        
        [_assetsLibrary writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)image.imageOrientation completionBlock:^(NSURL *assetURL, NSError *error) {
            if (error) {
                NSLog(@"%@", [error description]);
                NSLog(@"Save image fail:%@",error);
            }else{
                NSLog(@"Save image succeed.");
                [_listImages removeObjectAtIndex:0];
                NSLog(@"one image saved");
                [self saveNext];
            }
        }];
        
    }
    else {
        [self allDone];
    }
}

-(void) savedPhotoImage:(UIImage*)image didFinishSavingWithError: (NSError *)error contextInfo: (void *)contextInfo {
    if (error) {
        //NSLog(@"%@", error.localizedDescription);
        //        [error description]
        NSLog(@"%@", [error description]);
    }
    else {
        [_listImages removeObjectAtIndex:0];
        NSLog(@"one image saved");
    }
    [self saveNext];
}

- (void)allDone
{
    NSLog(@"allDone --###");
}

- ( void )showError:( int )errCode {
    UIAlertView *alert = [[ UIAlertView alloc ] initWithTitle:@"Error while encode"
                                                      message:[ giflib_ios getErrorDescription:errCode ]
                                                     delegate:nil
                                            cancelButtonTitle:@"Cancel"
                                            otherButtonTitles:nil ];
    [ alert show ];
//    [ alert release ];
    [ self performSelectorOnMainThread:@selector( dismissLockView )
                            withObject:nil
                         waitUntilDone:NO ];
}

@end

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值