使用SDWebImage加载多个图片内存崩溃的问题

使用SDWebImage加载多个图片时,在加载的过程中,当图片分辨率比较大的时候,加载几张图片就崩溃了。需要对图片进行处理,避免内存崩溃问题。

一、预加载图片URL数组

预加载URL数组

    [[SDWebImagePrefetcher sharedImagePrefetcher] prefetchURLs:array progress:^(NSUInteger noOfFinishedUrls, NSUInteger noOfTotalUrls) {
        
    } completed:^(NSUInteger noOfFinishedUrls, NSUInteger noOfSkippedUrls) {
       
    }];

二、获取图片数组

NSMutableArray *imageArray = [NSMutableArray arrayWithArray:array];
for (NSInteger i = 0 ; i < array.count ; i++) {
    NSString *imageStr = array[i];
    NSURL *imgUrl = [NSURL URLWithString:imageStr];
    // 根据URL获取key值
    NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:imgUrl];
    if (key.length) {
//              UIImage *image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key];
        // 获取缓存中图片data
        NSData *data = [[SDImageCache sharedImageCache] diskImageDataForKey:key];
        UIImage *image = nil;
        CGFloat imgMaxSide = [UIScreen mainScreen].scale * 100;
        // 判断图片大小
        if (data.length > imgMaxSide * imgMaxSide * 4) {
            // 获取图片缓存路径
            NSString *cacheImagePath = [[SDImageCache sharedImageCache] cachePathForKey:key];
            if (cacheImagePath.length) {
                // 压缩图片
                image = [self thumbImageFromLargeFile:cacheImagePath withConfirmedMaxPixelSize:100];
            }
        } else {
            image = [UIImage imageWithData:data];
        }
        // 替换数组中的图片
        if (image == nil) {
            imageArray[i] = [UIImage imageNamed:@"default"];
        }else{
            imageArray[i] = image;
        }
    }
}

三、获取图片缩略图

/// 获取图片的缩略图
/// @param filePath 图片本地路径
/// @param maxPixelSize 图片最大像素宽度
- (UIImage *)thumbImageFromLargeFile:(NSString *)filePath withConfirmedMaxPixelSize:(CGFloat)maxPixelSize
{
    // Create the image source (from path)
    CGImageSourceRef src = CGImageSourceCreateWithURL((__bridge CFURLRef) [NSURL fileURLWithPath:filePath], NULL);
    
    // Create thumbnail options
    CFDictionaryRef options = (__bridge CFDictionaryRef) @{
        (id) kCGImageSourceCreateThumbnailWithTransform : @YES,
        (id) kCGImageSourceCreateThumbnailFromImageAlways : @YES,
        (id) kCGImageSourceThumbnailMaxPixelSize : @(maxPixelSize)
    };
    // Generate the thumbnail
    CGImageRef thumbnail = CGImageSourceCreateThumbnailAtIndex(src, 0, options);
    CFRelease(src);
    
    UIImage *image = [[UIImage alloc] initWithCGImage:thumbnail];
    CFRelease(thumbnail);
    return image;
}

你可能感兴趣的:(使用SDWebImage加载多个图片内存崩溃的问题)