使用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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值