Write IPTC data to file

前端 未结 2 1905
有刺的猬
有刺的猬 2021-01-06 17:02

I would need to take an existing jpg file and modify the title, the description and the keywords in its IPTC entries. There are several topics here on this but all either wi

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-06 17:56

    You should first read the metadata from the file:

    CGImageSourceRef source = CGImageSourceCreateWithURL((__bridge CFURLRef)url, NULL);
    NSDictionary *props = (__bridge_transfer NSDictionary *) CGImageSourceCopyPropertiesAtIndex(source, 0, NULL);
    

    In the code above, url is the URL of your image file. props will have all the metadata of the image at the destination URL.

    Then, you copy that data to a new mutable, empty data source:

    //new empty data to write the final image data to
    NSMutableData *resultData = [NSMutableData data];
    CGImageDestinationRef imgDest = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)(resultData), imageType, 1, NULL);
    

    Finally, let's assume you've modified the metadata in a new NSDictionary instance (called modifiedMetadata in this example):

    //copy image data
    CGImageDestinationAddImageFromSource(imgDest, source, 0, (__bridge CFDictionaryRef)(modifiedMetadata));
    BOOL success = CGImageDestinationFinalize(imgDest);
    

    This would write the metadata to the destination image. At least in my case, it works perfectly.

    To save the image data to an actual file, you can write the data regularly, e.g:

    [resultData writeToFile:fileName atomically:YES];
    

提交回复
热议问题