在 url 保存图像时 PHPhotoLibrary 错误

PHPhotoLibrary error while saving image at url

我在 PHContentEditingOutput 提供的 url 创建了一个图像。当我将数据加载到 UIImage 并像这样保存时 - 它有效。

[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
    NSData *data = [NSData dataWithContentsOfURL:contentEditingOutput.renderedContentURL]
    UIImage *image = [UIImage imageWithData:data];
    [PHAssetChangeRequest creationRequestForAssetFromImage:image];
} completionHandler:^(BOOL success, NSError *error) {
     ...
}];

但是当我尝试使用 url 方法时,它失败了:

[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
    [PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:contentEditingOutput.renderedContentURL];
} completionHandler:^(BOOL success, NSError *error) {
     ...
}];

错误:

Error Domain=NSCocoaErrorDomain Code=-1 "The operation couldn’t be completed. (Cocoa error -1.)"

更新:

当我尝试保存修改时出现同样的错误。

[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
    PHAssetChangeRequest *request = [PHAssetChangeRequest changeRequestForAsset:asset];
    request.contentEditingOutput = contentEditingOutput;
} completionHandler:^(BOOL success, NSError *error) {
     ...
}];

该方法适用于视频 (creationRequestForAssetFromVideoAtFileURL:),但不适用于图像。出了什么问题?

问题出在文件格式上。我试图编辑 PNG 屏幕截图,但 renderingContentURL 始终是 tmp/filename.JPG。起初我以为这是一个错误,但根据 the documentation 这是正确的行为。

renderedContentURL

Read this property to find a URL for writing edited asset content. Then, if editing a photo asset, write the altered photo image to a file in JPEG format at this URL. If editing a video asset, export the video to a QuickTime (.mov) file at this URL.

解决方法是用函数

转换图片
NSData *UIImageJPEGRepresentation(UIImage *image, CGFloat compressionQuality);

传递元数据时,只要方向(在图像元数据中)不是CGImagePropertyOrientationUp,我也会一直显示这个问题。

renderedContentURL 文档中也有说明:

Edited asset content must incorporate (or “bake in”) the intended orientation of the asset. That is, the orientation metadata (if any) that you write in the output image or video file must declare the “up” orientation, and the image or video data must appear right-side up when presented without orientation metadata.

对于图像,需要更新以下元数据键(同时旋转图像数据):
kCGImagePropertyTIFFDictionary \ kCGImagePropertyTIFFOrientation
kCGImagePropertyOrientation
• 可能 kCGImagePropertyIPTCImageOrientation