PHAsset转NSData

本文介绍了如何在iOS应用中将选中的图片保存至本地数据库,并通过图片标识符实现图片的再次加载。主要讨论了使用PHAsset的localIdentifier进行图片保存和检索的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


最近项目要增加一个草稿箱的功能,所以要把相册里的相关图片保存到本地数据库,急的同学,可跳过1和2,只看红色字部分粗略理解一下思路就OK了,直接看第3


1.  ALAsset/PHAsset 并不是真正的文件对象,他们仅仅包含真正文件的基本信息如:文件路径,文件元数据。这里有篇文章介绍比较详细:http://io.upyun.com/2016/03/23/the-real-files-in-alasset-and-phasset/  所以PHAsset是不可以直接转NSData的,而是要间接通过他的一个标识localIdentifier去转化、保存


2.  转化的思路这里有介绍:https://segmentfault.com/q/1010000005636505

但我想说一下,那个PHAsset的localIdentifier是PHAsset的父类的属性,你点进去PHAsset还要再看看他父类才看得到这个属性


3.  代码如下:

// 拿到PHAssets--localIdentifier标识,他是一个字符串,然后把这堆字符NSString串数组转化成NSData就可以了(字符串转NSData都不会?谷歌去吧)_selectedAssets是我自己保存PHAsset的可变数组---就是你保存了这堆图片的标识就等于保存了这堆图片的NSData,等于国家有你身份证号码,就有你的档案记录一样道理

    NSMutableArray *localIdentifier_Array = [NSMutableArray  array];

   for (PHAsset *phAsset  in  _selectedAssets) {

        [ localIdentifier_Array  addObject: phAsset.localIdentifier ];

    }

// 中间省略了字符串和NSData转化的代码,也可以说是字符串归档解档,由于自己封装起来的原因,不方便贴出来,但这个也比较简单,见谅


// 下面是取回本地保存的图片,也是一样道理,通过图片标识去取回,用这个方法fetchAssetsWithLocalIdentifiers取出来的其实也是类似一个数组,直接遍历就OK了

        PHFetchResult *phFetchResult = [PHAsset  fetchAssetsWithLocalIdentifiers:localIdentifier_Array  optionsnil ];

        [phFetchResult   enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx,BOOL *_Nonnull stop) {

            [ _selectedAssets  addObject: obj ];

        }];



处理下面代码可能出现线程问题的情况- (void)shutterCamera { AVCaptureConnection *videoConnection = [self.ImageOutPut connectionWithMediaType:AVMediaTypeVideo]; UIDeviceOrientation curDeviceOrientation = [[UIDevice currentDevice] orientation]; if (!videoConnection || !self.session.isRunning) { ATLog(@"take photo failed!"); return; } AVCaptureVideoOrientation avcaptureOrientation = [self avOrientationForDeviceOrientation:curDeviceOrientation]; [videoConnection setVideoOrientation:avcaptureOrientation]; [videoConnection setVideoScaleAndCropFactor:self.effectiveScale]; MJWeakSelf; [self.ImageOutPut captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) { dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ __strong typeof(weakSelf) strongSelf = weakSelf; if (!strongSelf) return; if (imageDataSampleBuffer) { NSData * imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer]; strongSelf.image = [UIImage imageWithData:imageData]; if (strongSelf.image) { strongSelf.image = [UIImage updateImageSize:strongSelf.image]; } strongSelf.image = [[TZImageManager manager] fixOrientation:strongSelf.image];//[UIImage fixOrientation:weakSelf.image]; PHAuthorizationStatus authorStatus = [PHPhotoLibrary authorizationStatus]; if (authorStatus == PHAuthorizationStatusAuthorized) { [[TZImageManager manager] savePhotoWithImage:strongSelf.image completion:^(PHAsset *asset, NSError *error) { [strongSelf addPHAsset:asset]; }]; }else{ [strongSelf gotoEditImageController:strongSelf.image asset:nil]; } } }); }]; } - (void)gotoEditImageController:(UIImage *)image asset:(PHAsset *)asset { if (!image) { [ATMBPHud showErrorToView:self.view text:@"获取图片失败,请重新再试"]; return; } if (image) { image = [UIImage updateImageSize:image]; } YasicClipPage *vc = [[YasicClipPage alloc] init]; vc.userId = self.userId; vc.attention = self.attention; vc.targetImage = image; vc.searchType = self.searchType; vc.asset = asset; // [self stopSession]; dispatch_async(dispatch_get_main_queue(), ^{ [[KDUserInterfaceTool currenrtopViewController].navigationController pushViewController:vc animated:YES]; [self removeViewController:self]; }); } - (void)addPHAsset:(PHAsset *)asset { MJWeakSelf; TZAssetModel *assetModel = [[TZImageManager manager] createModelWithAsset:asset]; [ATHUD show]; [[TZImageManager manager] requestImageDataForAsset:assetModel.asset completion:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) { [ATHUD dismiss]; UIImage *image = [UIImage imageWithData:imageData];//[[TZImageManager manager] fixOrientation:[UIImage imageWithData:imageData]]; image = [[TZImageManager manager] fixOrientation:image]; [weakSelf gotoEditImageController:image asset:asset]; } progressHandler:^(double progress, NSError *error, BOOL *stop, NSDictionary *info) { ATLog(@"%f",progress); }]; } #pragma --mark 获取大图 - (void)getImageWithModel:(TZAssetModel *)model { if (model == nil) { ATLog(@"图片为空"); return; } [ATHUD show]; WS(weakSelf) [[TZImageManager manager] requestImageDataForAsset:model.asset completion:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) { [ATHUD dismiss]; UIImage *image = [UIImage imageWithData:imageData]; if (weakSelf.downBtnClick) { weakSelf.downBtnClick(image, model); } } progressHandler:^(double progress, NSError *error, BOOL *stop, NSDictionary *info) { ATLog(@"%f",progress); }]; }
07-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值