在iOS中,要将UIImage
保存为JPEG,我使用UIImageJPEGRepresentation
,但它不接受压缩比以外的选项。我想将UIImage
保存为progressive JPEG
格式,有简单的方法吗?
在OS X中,似乎有一个NSImageProgressive
选项可以将NSImage
保存为渐进格式。
我认为您可以使用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"。
此代码在设备上确实有效-关键是指定所有密度值(注意它使用了新的文字语法):
- (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];
}