Я пытаюсь отредактировать метаданные фотографии камеры.
Однако, если вы попытаетесь перезаписать фотографию после редактирования метаданных, всегда выдает следующую ошибку:
'Error Domain=NSCocoaErrorDomain Code=-1 "Операция не может быть завершена. (Ошибка Cocoa -1.)"
Это происходит с фотографиями, такими как пейзажные изображения (с тегом ориентации «6»).
Для портретных изображений (тег ориентации «1») можно правильно перезаписывать и сохранять фотографии.
Если вы декодируете с помощью UIImageJPEGRepresentation (изображение, 1.0), пейзажные изображения могут быть перезаписаны и сохранены.
Но я не хочу снижать качество изображения, поэтому ищу другой способ.
Действия по воспроизведению:
Сохраните изображение фотопленки в разделе «Документы / 。».
Отредактируйте метаданные одной фотографии. (Отныне в разделе Документы/)
Получите актив «requestContentEditingInputWithOptions()».
Получите URL-адрес фотографии «Шаг 2» и получите CGImageSourceRef с помощью «CGImageSourceCreateWithURL ()».
Получите CGImageDestinationRef, указав contentEditingOutput.renderedContentURL с 'CGImageDestinationCreateWithURL ()'.
Задайте для CGImageSourceRef, CGImageDestinationRef и метаданных значение CGImageDestinationAddImageFromSource.
Сохраните CGImageDestinationRef с помощью CGImageDestinationFinalize.
Создайте PHAadjustmentData. Установите метаданные на «данные».
Установите AdjustmentData в setAdjustmentData
Установите набор в changeRequestForAsset библиотеки PHPhotoLibrary. → 'PHAssetChangeRequest * запрос = [PHAssetChangeRequest changeRequestForAsset: актив];'
'request.contentEditingOutput = contentEditingOutput;'
"завершение" - ошибка. следующая ошибка: 'Error Domain=NSCocoaErrorDomain Code=-1 "Операция не может быть завершенный. (Ошибка какао -1.)'
следуя коду:
- (void)replaceMetadataIntoPhoto:(NSInteger)index metadata:(NSDictionary *)metadata
{
PHAsset *asset = _assetsList[index];
[asset requestContentEditingInputWithOptions:nil
completionHandler:^(PHContentEditingInput *_Nullable contentEditingInput, NSDictionary *_Nonnull info) {
NSURL *url = [contentEditingInput fullSizeImageURL];
CGImageSourceRef sourceImage = CGImageSourceCreateWithURL((__bridge CFURLRef)url, nil);
PHContentEditingOutput *contentEditingOutput = [[PHContentEditingOutput alloc] initWithContentEditingInput:contentEditingInput];
CGImageDestinationRef outputDestination = CGImageDestinationCreateWithURL((__bridge CFURLRef)contentEditingOutput.renderedContentURL, CGImageSourceGetType(sourceImage), 1, NULL);
CGImageDestinationAddImageFromSource(outputDestination, sourceImage, 0, (__bridge CFDictionaryRef)metadata);
CGImageDestinationFinalize(outputDestination);
CFRelease(sourceImage);
CFRelease(outputDestination);
PHAdjustmentData *adjustmentData =
[[PHAdjustmentData alloc] initWithFormatIdentifier:@"hogehoge"
formatVersion:@"1.0"
data:[NSKeyedArchiver archivedDataWithRootObject:@{@"metadata": metadata}]];
[contentEditingOutput setAdjustmentData:adjustmentData];
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetChangeRequest *request = [PHAssetChangeRequest changeRequestForAsset:asset];
request.contentEditingOutput = contentEditingOutput;
} completionHandler:^(BOOL success, NSError *error) {
if (error) {
DBGLog(@"error=%@", error);
}
}];
Ожидаемые результаты:
Возможность перезаписать и сохранить ландшафтное изображение с отредактированными метаданными в фотопленке.
Фактические результаты:
Не удается перезаписать сохранение.
Я получил ответ от Apple Feedback Assistant. Ниже приведена цитата.
Please refer to https://developer.apple.com/documentation/photokit/phcontenteditingoutput/1518655-renderedcontenturl Important 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. If you want to rewrite orientation metadata in the EXIF or otherwise, you should try creating a new asset, rather than using PHContentEditingOutput.