图片作为超级吃流量的东东,如何避免它重复下载和占用大量内存打开图片呢?如何避免图片本地没有正在下载过程而重复下载呢?
图像压缩保存与压缩显示:通常使用UIImagePNGRepresentation的方式保存本地文件,它的好处是若该图片背景为透明可以保证它的背景仍旧透明,若使用UIImageJPEGRepresentation(image, 1)这种压缩保存的方式,保存的图像都是白背景,好处是图像质量可以改变,进而实现类似图像的压缩,但是压缩率不可控,不同图像压缩的比例不同。可以通过指定图像的边框来压缩图像显示在内存中,防止把一个很大的图像直接加载如内存,造成内存暴涨。如:UIImage *image = [AppManager resizeImage:[UIImage imageNamed:@”my_backgroud_up_6.png”] toSize:CGSizeMake(WINDOW_WIDTH, 64) scale:1];
图像压缩的方法例子:
//change size + (UIImage *)resizeImage:(UIImage *)image toSize:(CGSize)scaleSize scale:(CGFloat)scale { CGSize originalSize = image.size; CGSize newSize; if (scale == 1) { newSize = CGSizeMake(scaleSize.width, scaleSize.height); } else { newSize = CGSizeMake(originalSize.width * scale, originalSize.height * scale); } CGFloat newScale = scale; while (newScale > 0.1 && (newSize.width > scaleSize.width || newSize.height > scaleSize.height)) { newScale -= 0.05; newSize = CGSizeMake(newSize.width * scale, newSize.height * scale); } // Scale the original image to match the new size. UIGraphicsBeginImageContext(newSize); [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)]; UIImage* compressedImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return compressedImage; } //1、生成指定尺寸的图片 + (UIImage *)compressImage:(UIImage *)imgSrc :(CGSize)size { UIGraphicsBeginImageContext(size); CGRect rect = {{0,0}, size}; [imgSrc drawInRect:rect]; UIImage *compressedImg = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return compressedImg; } //2、生成指定大小图片 +(UIImage *)Rarimage:(UIImage *)orginImage compressionQuality:(float)compressionQuality { NSData *imageData = [[NSData alloc] initWithData:UIImageJPEGRepresentation(orginImage, compressionQuality)]; //如果图片小于50k 且尺寸>500直接输出 否则压缩 if (imageData.length>50000) { UIImage *image = [UIImage imageWithData:imageData]; //如果图片尺寸过大 尺寸等比例压缩 if (image.size.height>500 ||image.size.width>500) { UIGraphicsBeginImageContext(CGSizeMake(image.size.width * 0.3, image.size.height * 0.3)); [image drawInRect:CGRectMake(0, 0, image.size.width * 0.3, image.size.height * 0.3)]; image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); // NSData *imageData2 = [[NSData alloc] initWithData:UIImageJPEGRepresentation(image, compressionQuality)]; } return image; }else { return orginImage; } return nil; }
这个是我写的代码关于这个问题的解决方案及流程图。
刷新新订单时,订单有商家组Icon但是本地没有商家组Icon,异步下载商家组Icon,下载期间暂时不显示商家组Icon(也可以显示下载中默认商家组Icon),下载成功显示商家组Icon,下载失败不显示商家组Icon(也可以显示下载中默认商家组Icon)。当一次刷到多个订单,有多个订单有商家组Icon,这些商家组Icon有重复的,有些商家组Icon本地不存在,那么下载商家组Icon时,保证相同的商家组Icon不重复下载。