美文网首页
iOS 简易图片缓存

iOS 简易图片缓存

作者: 移动的键盘 | 来源:发表于2023-06-24 16:24 被阅读0次

图片url作为key存储本地,每次下载本地查找,有值返回并下载新图做对比,图片有变化更新,无值下载存储本地
代码

#import "UIImageView+CALImageView.h"
#import <CommonCrypto/CommonDigest.h>

@implementation UIImageView (CALImageView)

- (void)cal_imageWithUrl:(NSString *)url placeHolederImage:(UIImage *)placeHolderImage
{
    if (placeHolderImage) {
        self.image = placeHolderImage;
    }
    NSData *data = [self imageWithURL:url];
    UIImage *image = [UIImage imageWithData:data];
    if (image) {
        __weak typeof(self) weakSelf = self;
        [self compareImage:data url:url complete:^(NSData * _Nullable data1) {
            [weakSelf mainQueue:^{
                UIImage *newImage =  [UIImage imageWithData:data1];
                if (newImage) {
                    weakSelf.image  = newImage;
                }
            }];
        }];
        self.image = image;
    }
}

- (NSString *)hashKey:(NSString *)url
{
    NSString *key = [self getSHA256Str:url];
    return key;
}

- (NSData *)imageWithURL:(NSString *)url
{
    if (!url) {
        return nil;
    }
    NSString *key = [self hashKey:url];
    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    if (data) {
        return data;
    }else {
        NSURL *imageURL = [NSURL URLWithString:url];
        NSData *data = [[NSData alloc] initWithContentsOfURL:imageURL];
        [self saveImage:url data:data];
        return data;
    }
}

- (void)mainQueue:(void(^)(void))mainQueue
{
    NSThread *thread = [NSThread currentThread];
    if ([thread.name isEqualToString:@"main"]) {
        mainQueue();
    }else {
        dispatch_async(dispatch_get_main_queue(), mainQueue);
    }
}

- (NSString *)getSHA256Str:(NSString *)str
{
    const char *data = str.UTF8String;
    unsigned char result[CC_SHA256_DIGEST_LENGTH];
    CC_SHA256(data, (CC_LONG)strlen(data), result);
    NSMutableString *hashBuffer = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
        [hashBuffer appendFormat:@"%02x", result[i]];
    }
    return hashBuffer.mutableCopy;
}

- (void)saveImage:(NSString *)url data:(NSData *)data
{
    if (data) {
        NSString *key = [self hashKey:url];
        [[NSUserDefaults standardUserDefaults] setObject:data forKey:key];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

- (void)downLoadImage:(NSString *)url complete:(nonnull void (^)(NSData *_Nullable data))complete
{
    dispatch_async(dispatch_queue_create("YXHNTacsImageCache", DISPATCH_QUEUE_SERIAL), ^{
        NSURL *imageURL = [NSURL URLWithString:url];
        NSData *data = [[NSData alloc] initWithContentsOfURL:imageURL];
        complete(data);
    });
}

- (void)compareImage:(NSData *)oldData url:(NSString *)url complete:(nonnull void (^)(NSData *_Nullable data))complete
{
    [self downLoadImage:url complete:^(NSData * _Nullable data) {
        if (data) {
            UIImage *oldImage = [UIImage imageWithData:oldData];
            UIImage *newImage = [UIImage imageWithData:data];
            if (!newImage) {
                return;
            }
            UIImage *image1 = [self OriginImage:oldImage scaleToSize:CGSizeMake(8, 8)];
            NSString *oldHash = [self myHash:image1];
            UIImage *image2 = [self OriginImage:newImage scaleToSize:CGSizeMake(8, 8)];
            NSString *newHash = [self myHash:image2];
            if ([oldHash compare:newHash] != NSOrderedSame) {
                NSMutableArray *deffrentArr = [NSMutableArray array];
                for (int i = 0; i < 64; i++) {
                    NSString *sub1 = [oldHash substringWithRange:NSMakeRange(i, 1)];
                    NSString *sub2 = [newHash substringWithRange:NSMakeRange(i, 1)];
                    if (![sub1 isEqualToString:sub2]) {
                        [deffrentArr addObject:@(i)];
                    }
                }
                if (deffrentArr.count >= 10) {
                    complete(data);
                    [self saveImage:url data:data];
                }
            }
            
        }
    }];
}

- (UIImage *)OriginImage:(UIImage *)image scaleToSize:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return [self getGrayImage:scaledImage];
}

- (UIImage *)getGrayImage:(UIImage *)sourceImage
{
    int width = sourceImage.size.width;
    int height = sourceImage.size.height;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGContextRef context = CGBitmapContextCreate (nil,width,height,8,0,colorSpace,kCGImageAlphaNone);
    CGColorSpaceRelease(colorSpace);
    if (context == NULL) {
        return nil;
    }
    CGContextDrawImage(context,CGRectMake(0, 0, width, height), sourceImage.CGImage);
    UIImage *grayImage = [UIImage imageWithCGImage:CGBitmapContextCreateImage(context)];
    CGContextRelease(context);
    return grayImage;
}

- (NSString *)myHash:(UIImage *)img
{
    unsigned char* pixelData = [self grayscalePixels:img];
    
    int total = 0;
    int ave = 0;
    for (int i = 0; i < img.size.height; i++) {
        for (int j = 0; j < img.size.width; j++) {
            total += (int)pixelData[(i*((int)img.size.width))+j];
        }
    }
    ave = total/64;
    NSMutableString *result = [[NSMutableString alloc] init];
    for (int i = 0; i < img.size.height; i++) {
        for (int j = 0; j < img.size.width; j++) {
            int a = (int)pixelData[(i*((int)img.size.width))+j];
            if(a >= ave)
            {
                [result appendString:@"1"];
            }
            else
            {
                [result appendString:@"0"];
            }
        }
    }
    return result;
}

- (unsigned char *)grayscalePixels:(UIImage *)image
{
    // The amount of bits per pixel, in this case we are doing grayscale so 1 byte = 8 bits
#define BITS_PER_PIXEL 8
    // The amount of bits per component, in this it is the same as the bitsPerPixel because only 1 byte represents a pixel
#define BITS_PER_COMPONENT (BITS_PER_PIXEL)
    // The amount of bytes per pixel, not really sure why it asks for this as well but it's basically the bitsPerPixel divided by the bits per component (making 1 in this case)
#define BYTES_PER_PIXEL (BITS_PER_PIXEL/BITS_PER_COMPONENT)
    
    // Define the colour space (in this case it's gray)
    CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceGray();
    
    // Find out the number of bytes per row (it's just the width times the number of bytes per pixel)
    size_t bytesPerRow = image.size.width * BYTES_PER_PIXEL;
    // Allocate the appropriate amount of memory to hold the bitmap context
    unsigned char* bitmapData = (unsigned char*) malloc(bytesPerRow*image.size.height);
    
    // Create the bitmap context, we set the alpha to none here to tell the bitmap we don't care about alpha values
    CGContextRef context = CGBitmapContextCreate(bitmapData,image.size.width,image.size.height,BITS_PER_COMPONENT,bytesPerRow,colourSpace,kCGImageAlphaNone);
    
    // We are done with the colour space now so no point in keeping it around
    CGColorSpaceRelease(colourSpace);
    
    // Create a CGRect to define the amount of pixels we want
    CGRect rect = CGRectMake(0.0,0.0,image.size.width,image.size.height);
    // Draw the bitmap context using the rectangle we just created as a bounds and the Core Graphics Image as the image source
    CGContextDrawImage(context,rect,image.CGImage);
    // Obtain the pixel data from the bitmap context
    unsigned char* pixelData = (unsigned char*)CGBitmapContextGetData(context);
    
    // Release the bitmap context because we are done using it
    CGContextRelease(context);
    
    return pixelData;
#undef BITS_PER_PIXEL
#undef BITS_PER_COMPONENT
}

@end

相关文章

网友评论

      本文标题:iOS 简易图片缓存

      本文链接:https://www.haomeiwen.com/subject/ueybydtx.html