将图像从照片库复制到另一个目录

时间:2014-04-23 18:44:52

标签: ios objective-c nsdata

我想将图片从照片库复制到我的应用程序中的另一个目录,每件事情都可以正常使用附加代码,但是当我尝试复制大量图片时,应用程序立即崩溃我认为因为附带代码是用一个线程完成的,所以每个图像都需要它的线程,所以如果有太多的图片要复制应用程序崩溃。 我需要相同的代码,但不是在一个线程,这意味着应该阻止应用程序,直到图像被复制到另一个目录,如果任何人有另一个好主意,我将不胜感激。 for循环保存每个图像。

for (int i = 0; i< countt ;i++) {

        NSURL *referenceURL = [self.ToSaveArray objectAtIndex:i];
        ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
        [assetLibrary assetForURL:referenceURL resultBlock:^(ALAsset *asset) {
            ALAssetRepresentation *rep = [asset defaultRepresentation];
            Byte *buffer = (Byte*)malloc(rep.size);
            NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:rep.size error:nil];
            NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];//this is NSData may be what you want
            NSLog(@"length %d",[data length]);
            UIImage *image= [UIImage imageWithData:data];
            [self SavePhoto:image withnum:i];
            //[data writeToFile:photoFile atomically:YES];//you can save image later
        } failureBlock:^(NSError *err) {
            NSLog(@"Error: %@",[err localizedDescription]);
        }];

    }

保存照片代码:

-(bool)SavePhoto:(UIImage *) imageTosave withnum:(int)num{


    float goodScal = imageTosave.size.width/75.0;

    CGSize newSize =CGSizeMake(imageTosave.size.width/goodScal, imageTosave.size.height/goodScal);
    UIImage* smallImage = [self resizeImage:imageTosave toSize:newSize];
    NSData *JpgDataS = UIImageJPEGRepresentation(smallImage, 1);
    NSData *JpgData = UIImageJPEGRepresentation(imageTosave, 1);



    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
    NSString *dataPath = [documentsPath stringByAppendingPathComponent:@"/CapturesPhotos"];
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init]autorelease];
    NSTimeZone *zone = [NSTimeZone localTimeZone];
    [formatter setTimeZone:zone];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString* Bnamee = [NSString stringWithFormat:@"/IMG%d_%@B.jpg",num,[formatter stringFromDate:date]];
    NSString* Snamee = [NSString stringWithFormat:@"/IMG%d_%@S.jpg",num,[formatter stringFromDate:date]];
    //NSString *filePath = [dataPath stringByAppendingPathComponent:namee]; //Add the file name
    NSString *filePath = [dataPath stringByAppendingPathComponent:Bnamee]; //Add the file name
    NSString *filePathS = [dataPath stringByAppendingPathComponent:Snamee]; //Add the file name
    [JpgData writeToFile:filePath atomically:YES]; //Write the file
    [JpgDataS writeToFile:filePathS atomically:YES]; //Write the file
    //[pngData writeToFile:filePath atomically:YES]; //Write the file
    return true;
}

提前致谢

1 个答案:

答案 0 :(得分:1)

似乎很可能从许多异步操作开始运行你的内存不足,尝试使用串行队列序列化它的昂贵(内存)部分:

dispatch_queue_t    queue = dispatch_queue_create("save", DISPATCH_QUEUE_SERIAL);

// Move this out of loop for efficiency
ALAssetsLibrary*    assetLibrary=[[ALAssetsLibrary alloc] init];

for (int i = 0; i< ToSaveArray.count ;i++) {

    NSURL *referenceURL = [ToSaveArray objectAtIndex:i];
    [assetLibrary assetForURL:referenceURL resultBlock:^(ALAsset *asset) {
        ALAssetRepresentation *rep = [asset defaultRepresentation];
        dispatch_async(queue, ^{

            Byte *buffer = (Byte*)malloc(rep.size);
            NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:rep.size error:nil];
            NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];//this is NSData may be what you want
            NSLog(@"length %d",[data length]);
            UIImage *image= [UIImage imageWithData:data];
            [self SavePhoto:image withnum:i];
        });
        //[data writeToFile:photoFile atomically:YES];//you can save image later
    } failureBlock:^(NSError *err) {
        NSLog(@"Error: %@",[err localizedDescription]);
    }];

}

dispatch_async(queue, ^{
    // Some code to execute when all the saving is done
});

我不确定这是否能真正解决问题,但值得尝试:)

此外,如何更清晰地获取UIImage的更正版本(来自this answer):

UIImage*            image = [UIImage imageWithCGImage:[rep fullResolutionImage]
                                                scale:[rep scale]
                                          orientation:UIImageOrientationUp];

虽然在你的情况下,继续提取图像数据本身可能更好,但只需将其传递到保存例程中,这样就可以节省转换jpg-&gt; image-&gt; jpg的费用。你仍然需要创建图像,这样你也可以保存缩略图,但这是另一回事。