存储图片到photo library与存储video到photo library的API差不多,但也有所不同。图片是可以直接把数据写入photo library,而video需要先把数据存到临时文件然后,然后通过临时文件的路径去转存到photo library。
我们直接来看相应的API:
// These methods can be used to add photos or videos to the saved photos album.
// With a UIImage, the API user can use -[UIImage CGImage] to get a CGImageRef, and cast -[UIImage imageOrientation] to ALAssetOrientation.
- (void)writeImageToSavedPhotosAlbum:(CGImageRef)imageRef orientation:(ALAssetOrientation)orientation completionBlock:(ALAssetsLibraryWriteImageCompletionBlock)completionBlock;
// The API user will have to specify the orientation key in the metadata dictionary to preserve the orientation of the image
- (void)writeImageToSavedPhotosAlbum:(CGImageRef)imageRef metadata:(NSDictionary *)metadata completionBlock:(ALAssetsLibraryWriteImageCompletionBlock)completionBlock __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_4_1);
// If there is a conflict between the metadata in the image data and the metadata dictionary, the image data metadata values will be overwritten
- (void)writeImageDataToSavedPhotosAlbum:(NSData *)imageData metadata:(NSDictionary *)metadata completionBlock:(ALAssetsLibraryWriteImageCompletionBlock)completionBlock __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_4_1);
- (void)writeVideoAtPathToSavedPhotosAlbum:(NSURL *)videoPathURL completionBlock:(ALAssetsLibraryWriteVideoCompletionBlock)completionBlock;
最后一个是存储视频的API,可以看到参数是一个NSURL,这个只要穿一个本地临时文件的file URL 就好了。
存储图片根据你的需求选择适当的API,比如我们获取到的是UIImage的实例,那么我们用第一个或者第二个比较方便,如果我们从本地临时文件读取image的数据那么我们直接用第三个就比较方便。
下面来一段简单的代码:
- (void)saveImage:(UIImage*)image{
ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc]init];
[assetsLibrary writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)image.imageOrientation completionBlock:^(NSURL *assetURL, NSError *error) {
if (error) {
NSLog(@"Save image fail:%@",error);
}else{
NSLog(@"Save image succeed.");
}
}];
}
关于写入临时文件,我之前写过一篇关于文件读写的文章,可以去看看。
我这里奉上一个把工程资源库的video写入photo library的demo,这样你就可以把video导入模拟器了,方便有些时候测试。
主要代码如下,整个工程可以再文尾链接下载:
- (void)save:(NSString*)urlString{
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeVideoAtPathToSavedPhotosAlbum:[NSURL fileURLWithPath:urlString]
completionBlock:^(NSURL *assetURL, NSError *error) {
if (error) {
NSLog(@"Save video fail:%@",error);
} else {
NSLog(@"Save video succeed.");
}
}];
}
整个工程附在后面:
SaveVideo2PhotoLibrary(点击下载)