iOS 开发:保存UIImage到磁盘,内存不增长,使用ImageIO存UIImage

ImageIO是苹果出的图片处理 库,使用ImageIO保存图片到本地路径有一个好处是内存不会增长(传统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循环结束。
    @autoreleasepool {
        /// 构造保存URL
        NSURL* fileUrl = [NSURL fileURLWithPath:imagePath];
        CFURLRef url = (__bridge CFURLRef)fileUrl;
        
        /// 构造保存参数
        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;
        }
        
        /// 检查路径,如果路径不存在,先创建路径
        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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容