使用 PHPhotoLibrary,您可以从相机胶卷中替换特定 PHasset 的图像。
-(void) replaceimagefromcameraroll :(PHAsset*)replaceasset {
PHAsset *asset = replaceasset;
NSString *localStr=asset.localIdentifier;
NSRange range = [localStr rangeOfString:@"/"];
NSString *newString = [localStr substringToIndex:range.location];
NSString *appendedString=[NSString stringWithFormat:@"%@%@%@",@"assets-library://asset/asset.JPG?id=",newString,@"&ext=JPG"];
NSLog(@"%@ phasset ",appendedString);
NSURL *ReplaceAsseturl = [NSURL URLWithString:appendedString];
PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:@[ReplaceAsseturl] options:nil];
PHAsset *assetReplace = result.firstObject;
if ([assetReplace canPerformEditOperation:PHAssetEditOperationContent])
{
[asset requestContentEditingInputWithOptions:nil completionHandler:^(PHContentEditingInput *contentEditingInput, NSDictionary *info) {
PHContentEditingOutput *contentEditingOutput = [[PHContentEditingOutput alloc] initWithContentEditingInput:contentEditingInput];
UIGraphicsBeginImageContextWithOptions(_imgPreviewView.bounds.size, NO, 0.0);
[_imgPreviewView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *outputData = UIImageJPEGRepresentation(img, img.scale);
PHAdjustmentData *adjustmentData = [[PHAdjustmentData alloc] initWithFormatIdentifier:@"AdjustementDataIdentifier" formatVersion:@"1.0" data:outputData];
contentEditingOutput.adjustmentData = adjustmentData;
BOOL wrote = [outputData writeToURL:contentEditingOutput.renderedContentURL options:NSDataWritingAtomic error:nil];
[SVProgressHUD dismiss];
if (wrote)
{
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetChangeRequest *request = [PHAssetChangeRequest changeRequestForAsset:asset];
request.contentEditingOutput = contentEditingOutput;
} completionHandler:^(BOOL success, NSError *error) {
// console output : 1
if (success){
NSLog(@"success : %@", @(success));
[SVProgressHUD showSuccessWithStatus:ckSuccesReplaceImage];
}
else{
NSLog(@"error : %@", error);
}
}];
}
}];
}
}
而且你不要忘记在 Info.plist 文件中添加此代码
<key>NSPhotoLibraryUsageDescription</key>
<string>$(PRODUCT_NAME) would like to access your photo library to let you select a picture.</string>