UIImage数组中的数百张图片 - 内存泄漏



我正在开发一个应用程序,该应用程序可以从录制的视频中创建帧:

var videoFrames:[UIImage] = [UIImage]()
func loadImages(){
let generator = AVAssetImageGenerator(asset: asset)
generator.generateCGImagesAsynchronously(forTimes: capturedFrames, completionHandler: {requestedTime, image, actualTime, result, error in
DispatchQueue.main.async {
if let image = image {
self.videoFrames.append(UIImage(cgImage: image))                }
}
})
}

代码适用于最多加载 +/- 300 张图像。 当有更多时,应用程序由于内存问题而终止 - 我对 swift 相当陌生 - 如何进一步调试它?

有没有更好的方法来存储这么多图像?拆分为多个数组可以解决问题吗?

我的目标是有效地存储数千张照片(高达 1920x1080) - 也许您可以推荐一些更好的方法?

将映像写入磁盘并维护具有映像名称和路径的数据库。

if let image = image {
let uiImage = UIImage(cgImage: image)
let fileURL = URL(fileURLWithPath: ("__file_path__" + "(actualTime).png"))
uiImage.pngData()!.write(to: fileURL)
//write filepath and image name to database
}

我正在添加我的一些代码,这是我从未发布的应用程序中的旧代码。它在objC中,但概念仍然有效,发布的其他代码之间的主要区别在于处理程序还考虑了捕获视频的方向,当然您必须为方向变量提供一个值。

__block int i = 0;
AVAssetImageGeneratorCompletionHandler handler = ^(CMTime requestedTime, CGImageRef im, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error){
if (result == AVAssetImageGeneratorSucceeded) {
NSMutableDictionary * metadata = @{}.mutableCopy;
[metadata setObject:@(recordingOrientation) forKey:(NSString*)kCGImagePropertyOrientation];;
NSString * path = [mainPath stringByAppendingPathComponent:[NSString stringWithFormat:@"Image_%.5ld.jpg",(long)i]];
CFURLRef url = (__bridge_retained CFURLRef)[NSURL fileURLWithPath:path];
CFMutableDictionaryRef metadataImage = (__bridge_retained CFMutableDictionaryRef) metadata;
CGImageDestinationRef destination = CGImageDestinationCreateWithURL(url, kUTTypeJPEG, 1, NULL);
CGImageDestinationAddImage(destination, im, metadataImage);
if (!CGImageDestinationFinalize(destination)) {
DLog(@"Failed to write image to %@", path);
}
else {
DLog(@"Writing image to %@", path);
}
}
if (result == AVAssetImageGeneratorFailed) {
//DLog(@"Failed with error: %@ code %d", [error localizedDescription],error.code)
DLog(@"Failed with error: %@ code %ld for CMTime requested %@ and CMTime actual %@", [error localizedDescription],(long)error.code, CFAutorelease( CMTimeCopyDescription(kCFAllocatorDefault, requestedTime)), CFAutorelease(CMTimeCopyDescription(kCFAllocatorDefault,actualTime)));
DLog(@"Asset %@",videoAsset);
}
if (result == AVAssetImageGeneratorCancelled) {
NSLog(@"Canceled");
}
++i;
}

最新更新