簡體   English   中英

從圖庫中生成所有視頻的視頻縮略圖會導致內存問題

[英]Generating video thumbnails of all videos from gallery gives memory issues

我正在一個應用程序上需要顯示圖庫中所有視頻的縮略圖(以收藏夾視圖查看)。現在我正在使用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);

}

我想知道為什么我在這里遇到內存問題以及如何解決它。

似乎沒人知道正確的答案。 因此,在這里我經過一些研究后回答了自己的問題。

注意:要做到這一點,您不需要使用AVAssetImageGenerator。您可以使用以下方法來代替(PHOTOS FRAMEWORK)。

PHCachingImageManager *cachingImageManager;

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

這里使用的類是PHCachingImageManager,請參閱Apple文檔中的內容。

然后,使用第二種方法從緩存中檢索數據。

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

        cell.myImageView.image = result;
    }];

回調處理程序提供一個圖像,您可以在集合視圖單元格中使用。在cellForItemAtIndexPath方法中使用此圖像。

有關完整的代碼和參考,請參考APPLE的此示例。 https://developer.apple.com/library/ios/samplecode/UsingPhotosFramework/Introduction/Intro.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM