如何在iOS中将UIImage保存为渐进式JPEG格式?

时间:2012-03-21 22:58:38

标签: iphone objective-c ios uiimage jpeg

在iOS中将UIImage保存为JPEG,我使用UIImageJPEGRepresentation,但它不会采用除压缩比之外的其他选项。我希望将UIImage保存为progressive JPEG格式,有没有简单的方法可以这样做?

在OS X中看起来有一个NSImageProgressive选项可以将NSImage保存为渐进格式。

2 个答案:

答案 0 :(得分:8)

我认为您可以使用ImageIO框架来实现,如下所示:

#import <UIKit/UIKit.h>
#import <ImageIO/ImageIO.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "AppDelegate.h"

int main(int argc, char *argv[])
{
    @autoreleasepool {
        UIImage *sourceImage = [UIImage imageNamed:@"test.jpg"];

        CFURLRef url = CFURLCreateWithString(NULL, CFSTR("file:///tmp/progressive.jpg"), NULL);
        CGImageDestinationRef destination = CGImageDestinationCreateWithURL(url, kUTTypeJPEG, 1, NULL);
        CFRelease(url);

        NSDictionary *jfifProperties = [NSDictionary dictionaryWithObjectsAndKeys:
            (__bridge id)kCFBooleanTrue, kCGImagePropertyJFIFIsProgressive,
            nil];

        NSDictionary *properties = [NSDictionary dictionaryWithObjectsAndKeys:
            [NSNumber numberWithFloat:.6], kCGImageDestinationLossyCompressionQuality,
            jfifProperties, kCGImagePropertyJFIFDictionary,
            nil];

        CGImageDestinationAddImage(destination, sourceImage.CGImage, (__bridge CFDictionaryRef)properties);
        CGImageDestinationFinalize(destination);
        CFRelease(destination);

        return 0;
    }
}

Preview.app表示输出文件是渐进式的,ImageMagick的identify命令表示它具有“Interlace:JPEG”。

答案 1 :(得分:0)

此代码适用于设备 - 关键是指定所有密度值(请注意使用新的文字语法):

- (UIImage *)imager
{
    UIImage *object = [UIImage imageNamed:@"Untitled.jpg"];
    NSString *str = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"Tester.jpg"];
    NSURL *url = [[NSURL alloc] initFileURLWithPath:str];

    CGImageDestinationRef destination = CGImageDestinationCreateWithURL((__bridge CFURLRef)url, kUTTypeJPEG, 1, NULL);

    NSDictionary *jfifProperties = [NSDictionary dictionaryWithObjectsAndKeys:
                                    @72, kCGImagePropertyJFIFXDensity,
                                    @72, kCGImagePropertyJFIFYDensity,
                                    @1, kCGImagePropertyJFIFDensityUnit,
                                    nil];

    NSDictionary *properties = [NSDictionary dictionaryWithObjectsAndKeys:
                                [NSNumber numberWithFloat:.5f], kCGImageDestinationLossyCompressionQuality,
                                jfifProperties, kCGImagePropertyJFIFDictionary,
                                nil];

    CGImageDestinationAddImage(destination, ((UIImage*)object).CGImage, (__bridge CFDictionaryRef)properties);
    CGImageDestinationFinalize(destination);
    CFRelease(destination);

    return [UIImage imageWithContentsOfFile:str];
}