如何在iOS上快速将ALAsset映像保存到磁盘?

Bor*_*zin 7 image disk save ios alasset

我正在使用ALAsset来检索这样的图像:

[[asset defaultRepresentation] fullResolutionImage]]
Run Code Online (Sandbox Code Playgroud)

这返回CGImageRef,我想尽快保存到磁盘...

解决方案1:

UIImage *currentImage = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullResolutionImage]];
NSData *currentImageData = UIImagePNGRepresentation(currentImage);
[currentImageData writeToFile:filePath atomically:YES];
Run Code Online (Sandbox Code Playgroud)

解决方案2:

CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:filePath];
CGImageDestinationRef destination = CGImageDestinationCreateWithURL(url, kUTTypePNG, 1, NULL);
CGImageDestinationAddImage(destination, [[asset defaultRepresentation] fullResolutionImage], nil);
CGImageDestinationFinalize(destination);
Run Code Online (Sandbox Code Playgroud)

问题是两种方法在设备上的执行速度都很慢.每张图像大约需要2秒才能执行此操作.这绝对是长久的.

问题:如何加快图像保存过程?或许还有更好的解决方案吗?

更新: 两种解决方案中性能的最佳改进是将图像保存为JPEG格式而不是PNG.所以对于解决方案1已经取代UIImagePNGRepresentationUIImageJPEGRepresentation.对于解决方案2已经取代kUTTypePNGkUTTypeJPEG.

另外值得注意的是,第二种解决方案比第一种解决方案更有效.

Gus*_*Ost 9

您可以只复制原始数据.
这样做的好处是不会重新编码文件,不会使文件变大,不会通过额外压缩而丢失质量并保留文件中的任何元数据.也应该是最快的方式.
假设你有theAsset和a filepath保存它.
还应该添加错误处理.

long long sizeOfRawDataInBytes = [[theAsset defaultRepresentation] size];
NSMutableData* rawData = [NSMutableData dataWithLength:(NSUInteger) sizeOfRawDataInBytes];
void* bufferPointer = [rawData mutableBytes];
NSError* error=nil;
[[theAsset defaultRepresentation] getBytes:bufferPointer 
                                fromOffset:0
                                    length:sizeOfRawDataInBytes
                                     error:&error];
if (error) 
{
    NSLog(@"Getting bytes failed with error: %@",error);
}
else 
{
    [rawData writeToFile:filepath 
              atomically:YES];
}
Run Code Online (Sandbox Code Playgroud)


Nic*_*sky 2

这是因为 PNG 压缩过程很慢,并且在 iPhone 的处理器上需要一段时间,特别是对于全尺寸摄影。