在Apple的Core Graphics / ImageIO框架中的CGImageDestination中设置JPEG压缩质量时没有效果

use*_*609 1 jpeg core-graphics objective-c ios

我正在编写 IOS 应用程序,需要将 CGImage 保存为 JPEG 文件。控制压缩质量很重要。

我已经编写了下面提供的函数。它有效,因为我得到了一个 JPEG 文件。但无论我设置什么压缩,我总是得到相同的结果。即文件大小始终相同。

谁能告诉我我做错了什么?

void CGImageWriteJPEG(CGImageRef image, NSString *path) {
    NSMutableData * data = [[NSMutableData alloc] init];
    CGImageDestinationRef destination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)data, kUTTypeJPEG, 1, NULL);

    float compression = .8; // What I put here does not seem to matter...

    CFStringRef myKeys[1];
    CFTypeRef   myValues[1];
    CFDictionaryRef myOptions = NULL;
    myKeys[0] = kCGImageDestinationLossyCompressionQuality;
    myValues[0] = CFNumberCreate(NULL, kCFNumberFloatType, &compression);
    myOptions = CFDictionaryCreate( NULL, (const void **)myKeys, (const void **)myValues, 1,
                               &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);


    CGImageDestinationSetProperties(destination, myOptions);
    CGImageDestinationAddImage(destination, image, nil);
    CGImageDestinationFinalize(destination);



    [data writeToURL:[NSURL fileURLWithPath:path] atomically:NO];

    CFRelease(destination);
    CFRelease(myOptions);
    CFRelease(myValues[0]);
}
Run Code Online (Sandbox Code Playgroud)

mrj*_*mrj 6

尝试将 myOptions 传递给 CGImageDestinationAddImage()

CGImageDestinationAddImage(destination, image, myOptions);
Run Code Online (Sandbox Code Playgroud)

这是我必须迅速做的事情,所以我认为这是一样的。例如

let imageProperties = [kCGImageDestinationLossyCompressionQuality as String: 0.8]
CGImageDestinationAddImage(destination, image, imageProperties)
Run Code Online (Sandbox Code Playgroud)

更新了 swift 3 的答案

let imageProperties = [kCGImageDestinationLossyCompressionQuality as String: 0.8] as CFDictionary
CGImageDestinationAddImage(destination, image, imageProperties)
Run Code Online (Sandbox Code Playgroud)