Технические вопросы и ответы QA1622

Доступ к Метаданным изображения в iOS

Q: Как я получаю метаданные изображения в iOS?

A: Ссылка класса UIImagePickerController позволяет разработчику предлагать пользователю делать снимок от камеры или выбирать существующее изображение из фото библиотеки. Начало в iOS 4.1 NSDictionary возразите, что возвраты Ссылки на протокол UIImagePickerControllerDelegate содержат NSDictionary это содержит метаданные фотографии, просто полученной в дополнение к UImage. Получить доступ к использованию словаря метаданных UIImagePickerControllerMediaMetadata ключ NSDictionary возвращенный UIImagePickerControllerDelegate. Для хранения метаданных вместе с изображением в Рулоне Камеры используйте метод Ссылки класса ALAssetsLibrary Ссылки Платформы Библиотеки Активов.

  Пример перечисления 1 доступа и сохранения метаданных изображения с UIImagePickerController.

// Respond to the user accepting a newly-captured picture
- (void) imagePickerController: (UIImagePickerController *) picker
 didFinishPickingMediaWithInfo: (NSDictionary *) info {

    NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    UIImage *originalImage, *editedImage, *imageToSave;

    // Handle a still image capture
    if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0)
        == kCFCompareEqualTo) {

        editedImage = (UIImage *) [info objectForKey:
                                   UIImagePickerControllerEditedImage];
        originalImage = (UIImage *) [info objectForKey:
                                     UIImagePickerControllerOriginalImage];

        if (editedImage) {
            imageToSave = editedImage;
        } else {
            imageToSave = originalImage;
        }

        // Get the image metadata
        UIImagePickerControllerSourceType pickerType = picker.sourceType;
        if(pickerType == UIImagePickerControllerSourceTypeCamera)
        {
            NSDictionary *imageMetadata = [info objectForKey:
                                           UIImagePickerControllerMediaMetadata];
            // Get the assets library
            ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
            ALAssetsLibraryWriteImageCompletionBlock imageWriteCompletionBlock =
            ^(NSURL *newURL, NSError *error) {
                if (error) {
                    NSLog( @"Error writing image with metadata to Photo Library: %@", error );
                } else {
                    NSLog( @"Wrote image with metadata to Photo Library");
                }
            };

            // Save the new image (original or edited) to the Camera Roll
            [library writeImageToSavedPhotosAlbum:[imageToSave CGImage] 
                                         metadata:imageMetadata 
                                  completionBlock:imageWriteCompletionBlock];
        }
    }


    [[picker parentViewController] dismissModalViewControllerAnimated: YES];
    [picker release];
}

Для доступа к метаданным существующих изображений в фото библиотеке, необходимо использовать Ссылку Платформы Библиотеки Активов, которая может использоваться для доступа к изображениям и видео, которыми управляет фото приложение включая их метаданные.

  Пример перечисления 2 доступа к метаданным изображения с платформой Библиотеки Активов.

// Get the assets library
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

// Enumerate just the photos and videos group by using ALAssetsGroupSavedPhotos.
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
                       usingBlock:^(ALAssetsGroup *group, BOOL *stop)
 {

     // Within the group enumeration block, filter to enumerate just photos.
     [group setAssetsFilter:[ALAssetsFilter allPhotos]];

     // For this example, we're only interested in the first item.
     [group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:0]
                             options:0
                          usingBlock:^(ALAsset *alAsset, NSUInteger index, BOOL *innerStop)
      {

          // The end of the enumeration is signaled by asset == nil.
          if (alAsset) {
              ALAssetRepresentation *representation = [alAsset defaultRepresentation];
              NSDictionary *imageMetadata = [representation metadata];
              // Do something interesting with the metadata.
          }
      }];
 }
                     failureBlock: ^(NSError *error)
 {
     // Typically you should handle an error more gracefully than this.
     NSLog(@"No groups");
 }];

[library release];


История версии документа


ДатаПримечания
22.08.2011

Обсуждает новый APIs, доступный в iOS 4 для доступа к метаданным изображения.

25.08.2009

Новый документ, описывающий, как получить доступ к метаданным изображения с помощью UIImagePickerController и Платформы Библиотеки Активов.