2017-06-06 94 views
1

我想複製一個uiimage並更改元數據,而不用重新編碼圖像,以便不會導致jpg工件(我知道下面的代碼重新編碼,但這只是爲了它可以運行測試)。 CGImageDestinationCopyImageSource應該複製圖像的來源而不用重新編碼它,但是當我使用該函數時,它在CGImageDestinationFinalize時失敗。我試圖按照這個技術說明https://developer.apple.com/library/content/qa/qa1895/_index.html 任何想法爲什麼CGImageDestinationFinalize會失敗,下面的代碼?CGImageDestinationFinalize使用CGImageDestinationCopyImageSource失敗

-(NSData *)copyImageAndChangeMetaData:(UIImage *)image { 

    NSData *imageData = UIImageJPEGRepresentation(image, 1.0); 

    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL); 
    NSLog(@" source: 0x%x", source); 
    if (source == NULL) { 
     NSLog(@" source is NULL"); 
    } 

    CFStringRef UTI = CGImageSourceGetType(source); 
    NSLog(@" UTI: %@", (__bridge NSString *)UTI); 
    if (UTI == NULL) { 
     NSLog(@" UTI is NULL"); 
    } 

    NSMutableData *dest_data = [NSMutableData data]; 
    CGImageDestinationRef destination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)dest_data, UTI, 1, NULL); 
    if (!destination) 
    { 
     NSLog(@"Image Data Error: Could not create image destination"); 
    } 

    CFMutableDictionaryRef metadata = CFDictionaryCreateMutable(kCFAllocatorDefault, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); 

    int orient = 8; 
    CFNumberRef orientRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &orient); 
    CFDictionarySetValue(metadata, kCGImageDestinationOrientation, orientRef); 

    CFStringRef dateStringRef = CFStringCreateWithCString(kCFAllocatorDefault, "2017-06-06T17:31:46Z", kCFStringEncodingASCII); 
    CFDictionarySetValue(metadata, kCGImageDestinationDateTime, dateStringRef); 

    CFErrorRef errorRef = nil; 
    if (!CGImageDestinationCopyImageSource(destination, source, metadata, &errorRef)) { 
     CFStringRef error_description = CFErrorCopyDescription(errorRef); 

     NSString *errorDescription = (__bridge NSString *)error_description; 
     NSLog(@"Image Data Error: Error copying image data: %@", errorDescription); 

     CFRelease(error_description); 
    } 

    BOOL success = NO; 
    success = CGImageDestinationFinalize(destination); 
    if (!success) 
    { 
     NSLog(@"Image Data Error: Could not finalize image"); 
    } 
    if (source != NULL) { 
     CFRelease(source); 
    } 

    if (destination != NULL) { 
     CFRelease(destination); 
    } 

    return dest_data; 
} 

回答

3

根據文件<ImageIO/CGImageDestination.h>蘋果HeaderDoc文檔CGImageDestinationCopyImageSource()功能:)

CGImageDestinationFinalize(不應該被稱爲後 - 結果保存到目的地時,該函數返回。

+0

這是一個非常奇怪的API,所有事情都考慮在內。 –