#import <MobileCoreServices/MobileCoreServices.h>
- (NSData *)asProgressiveJPEGDataWithCompression:(CGFloat)Compression {
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"progressive.jpg"];
NSURL *fileUrl = [NSURL fileURLWithPath:path isDirectory:YES];
CFURLRef url = CFURLCreateWithString(kCFAllocatorDefault, (__bridge CFStringRef)fileUrl.absoluteString, NULL);
NSDictionary *jfifProperties = @{(__bridge NSString*)kCGImagePropertyJFIFIsProgressive:@(YES)};
NSDictionary *properties = @{(__bridge NSString*)kCGImageDestinationLossyCompressionQuality:@(Compression),(__bridge NSString*)kCGImagePropertyJFIFDictionary:jfifProperties};
CGImageDestinationRef destinationRef = CGImageDestinationCreateWithURL(url, kUTTypeJPEG, 1, (__bridge CFDictionaryRef)properties);
CGImageDestinationAddImage(destinationRef, self.CGImage, (__bridge CFDictionaryRef)properties);
CGImageDestinationFinalize(destinationRef);
NSData *data = [NSData dataWithContentsOfFile:path];
if (data) {
return data;
} else {
return UIImageJPEGRepresentation(self, 1);
}
}
注意:再转换的过程中,不要再次用 UIImagePNGRepresentation 或 UIImageJPEGRepresentation去获取NSData。这样会会破坏修改,应该直接将NSData返回,上传服务器。