从库中生成所有视频的视频缩略图会产生内存问题

时间:2016-02-22 08:17:05

标签: ios gallery video-thumbnails avassetimagegenerator

我正在开发一个应用程序,我需要在我的库中显示所有视频的缩略图(被视为集合视图)。现在我正在使用AVAssetImageGenerator从图库中的视频生成缩略图,但我遇到了内存问题。这是我正在使用的代码:

    PHFetchResult *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeVideo options:nil];

    PHImageManager *imageManager = [PHImageManager new];

    for(NSInteger i=0 ; i < fetchResult.count ; i++){

     __weak SAVideosViewController *weakSelf = self;
        [imageManager requestAVAssetForVideo:fetchResult[i] options:nil resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {

            [collectionViewData addObject:asset];
//my method to generate video thumbnail...
            [self generateThumbnailForAsset:asset];

            if(i == fetchResult.count-1){

                collectionViewDataFilled = YES;

                 dispatch_async(dispatch_get_main_queue(), ^{

                    [weakSelf.myCollectionView reloadData];
                });

            }
        }];
    }

以下是上述方法:

    -(void)generateThumbnailForAsset:(AVAsset*)asset_{

AVAssetImageGenerator *imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset_];
    CMTime time = CMTimeMakeWithSeconds(1,1);
    CMTimeShow(time);
    CGImageRef img = [imageGenerator copyCGImageAtTime:time  actualTime:NULL error:NULL];

if(img != nil){
    NSLog(@"image");
    [thumbnails addObject:[UIImage imageWithCGImage:img]];
}

CGImageRelease(img);

}

我想知道为什么我在这里遇到内存问题以及如何解决它。

1 个答案:

答案 0 :(得分:2)

似乎没有人知道正确的答案。所以在这里我经过一些研究后回答了我自己的问题。

注意:要做这样的事情,您不需要使用AVAssetImageGenerator。您可以使用以下方法(PHOTOS FRAMEWORK)。

PHCachingImageManager *cachingImageManager;

[cachingImageManager startCachingImagesForAssets:collectionViewData targetSize:cellSize contentMode:PHImageContentModeAspectFill options:nil];

这里使用的类是PHCachingImageManager。在apple docs中有关于此的内容。

然后,使用第二种方法从缓存中检索数据。

    [cachingImageManager requestImageForAsset:collectionViewData[indexPath.row] targetSize:AssetGridThumbnailSize contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {

        cell.myImageView.image = result;
    }];

回调处理程序提供了一个可以在集合中使用的图像View cells.use this in cellForItemAtIndexPath method。

有关完整的代码和参考,请参阅APPLE的此示例。 https://developer.apple.com/library/ios/samplecode/UsingPhotosFramework/Introduction/Intro.html

相关问题