博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
2.7 保存图片到照片库
阅读量:689 次
发布时间:2019-03-21

本文共 1561 字,大约阅读时间需要 5 分钟。

文章目录

2.7 保存图片到照片库

当用户按下Save按钮,我们开启繁忙模式.然后,如果摄像头正在运行,我们准备保存下一帧图片.否则,我们立即保存当前处理过的静态图像,代码如下:

- (IBAction)onSaveButtonPressed{    [self startBusyMode];    if (self.videoCamera.running) {        self.saveNextFrame = YES;       }    else {        [self saveImage:self.imageView.image];    }}

帮助函数saveImage:,负责处理文件系统和图库之间的数据处理.首先,我们尝试写一个png文件到程序的临时目录.然后,我们尝试根据该文件在相册中创建一个图片.在这个处理过程中,文件会被自动拷贝.我们会调用另一个帮助方法来展示一个警告框来提示操作成功还是失败,下面是代码的实现:

- (void)saveImage:(UIImage *)image {    // Try to save the image to a temporary file.    NSString *outputPath = [NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), @"output.png"]; if (![UIImagePNGRepresentation(image) writeToFile:outputPath atomically:YES]) {        // Show an alert describing the failure.        [self showSaveImageFailureAlertWithMessage:@"The image could not be saved to the temporary directory."];        return;    }    // Try to add the image to the Photos library.    NSURL *outputURL = [NSURL URLWithString:outputPath];    PHPhotoLibrary *photoLibrary = [PHPhotoLibrary sharedPhotoLibrary];    [photoLibrary performChanges:^{        [PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:outputURL];    } completionHandler:^(BOOL success, NSError *error) {        if (success) {            // Show an alert describing the success, with sharing // options.            [self showSaveImageSuccessAlertWithImage:image];        }        else { // Show an alert describing the failure.            [self showSaveImageFailureAlertWithMessage:            error.localizedDescription];        }    }];}

转载地址:http://nmxez.baihongyu.com/

你可能感兴趣的文章