我正在开发一款能够根据录制的视频创建框架的应用程序:
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) - 也许您可以推荐一些更好的方法?
答案 0 :(得分:2)
将图像写入磁盘并使用图像名称和路径维护数据库。
if let image = image {
let uiImage = UIImage(cgImage: image)
let fileURL = URL(fileURLWithPath: ("__file_path__" + "\(actualTime).png"))
UIImagePNGRepresentation(uiImage).write(to: fileURL)
//write filepath and image name to database
}
答案 1 :(得分:1)
我添加了一些我的代码,它是我在一个从未发布的应用程序中的旧代码。它在objC中但概念仍然有效,其他代码之间的主要区别在于处理程序还考虑了捕获视频的方向,当然你必须给方向变量赋值。 / p>
__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;
}