ImageIO是蘋果出的圖片處理 庫,使用ImageIO保存圖片到本地路徑有一個好處是內存不會增長(傳統(tǒng)API存圖的時候,內存會有一個增長,增長大小為image的大小)
#import "YTImageTool.h"
#import <ImageIO/ImageIO.h>
@implementation YTImageTool
+ (BOOL)saveImagePNG:(UIImage*)image imagePath:(NSString*)imagePath
{
return [self _saveImage:image isJPEG:NO quality:1 imagePath:imagePath];
}
+ (BOOL)saveImageJPEG:(UIImage *)image quality:(CGFloat)quality imagePath:(NSString *)imagePath
{
return [self _saveImage:image isJPEG:YES quality:quality imagePath:imagePath];
}
+ (BOOL)_saveImage:(UIImage *)image isJPEG:(BOOL)isJPEG quality:(CGFloat)jpegQuality imagePath:(NSString *)imagePath
{
if (!image || !imagePath) return NO;
/// 構造一個自動釋放池,及時釋放內存,無需等待當前runloop循環(huán)結束。
@autoreleasepool {
/// 構造保存URL
NSURL* fileUrl = [NSURL fileURLWithPath:imagePath];
CFURLRef url = (__bridge CFURLRef)fileUrl;
/// 構造保存參數(shù)
CFStringRef type = kUTTypePNG;
CFDictionaryRef params = nil;
if (isJPEG) {
type = kUTTypeJPEG;
jpegQuality = MAX(MIN(1, jpegQuality), 0);
NSDictionary* mutableDict = @{(__bridge NSString*)kCGImageDestinationLossyCompressionQuality:@(jpegQuality)};
params = (__bridge CFDictionaryRef)mutableDict;
}
/// 檢查是否是文件路徑
if (!fileUrl.isFileURL) {
KS500WLog(@"save photo failed! path is not a file url, path:%@!",imagePath);
[imagePath stringByDeletingPathExtension];
return NO;
}
/// 檢查路徑,如果路徑不存在,先創(chuàng)建路徑
NSString* path = imagePath.stringByDeletingLastPathComponent;
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
[[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
}
/// 構造destination
CGImageDestinationRef destination = CGImageDestinationCreateWithURL(url, type, jpegQuality, NULL);
if (!destination) {
KS500WLog(@"save photo failed! create destination failed, path:%@!",imagePath);
return NO;
}
/// 保存
BOOL saveSuccess = YES;
CGImageDestinationAddImage(destination, image.CGImage, params);
if (!CGImageDestinationFinalize(destination)) {
KS500WLog(@"save photo failed, path:%@!",imagePath);
saveSuccess = NO;
}
CFRelease(destination);
return saveSuccess;
}
}
@end
git直接導入使用:https://github.com/jlstmac/ImageSave