[英]How to save a UIImage into progressive JPEG format in iOS?
在iOS UIImageJPEGRepresentation
UIImage
保存為JPEG,我使用UIImageJPEGRepresentation
,但是除了壓縮率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];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.