iOS 開發(fā):保存UIImage到磁盤,內存不增長,使用ImageIO存UIImage

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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容