使用SDWebImage加載圖片內存飚升 導致閃退問題
[[SDImageCache sharedImageCache] setShouldDecompressImages:NO];
[[SDWebImageDownloader sharedDownloader] setShouldDecompressImages:NO];
他說的意思大概是減壓縮圖片,并將圖片存到cache使得之后的加載更加快,效果更加好。但是問題就在于去壓縮這個操作,如果傳進的圖片分辨率特別的高,它的減壓縮會消耗大量的內存,按照帖子其他回復的綜合可以大概得出結論就是他會將圖片的每一個像素點都有一個空間存下它的各個通道值,雖然這個內存空間是由于CG重繪的時候alloc出來的,所以是存在于VM里的空間。因此這樣的處理會導致一個拇指大小的圖片都可能消耗上GB得內存。
幾百K的圖片,分辨率達到3000+*2000+,就多消耗了40M內存,如果是GIF圖,又是幀數比較高,分辨率比較高的,就會出現一個GIF圖500M甚至上GB得奇葩現象= =
UIImage+MultiFormat這個類里面添加如下壓縮方法,
+(UIImage *)compressImageWith:(UIImage *)image
{
float imageWidth = image.size.width;
float imageHeight = image.size.height;
float width = 640;
float height = image.size.height/(image.size.width/width);
float widthScale = imageWidth /width;
float heightScale = imageHeight /height;
// 創建一個bitmap的context
// 并把它設置成為當前正在使用的context
UIGraphicsBeginImageContext(CGSizeMake(width, height));
if (widthScale > heightScale) {
[image drawInRect:CGRectMake(0, 0, imageWidth /heightScale , height)];
}
else {
[image drawInRect:CGRectMake(0, 0, width , imageHeight /widthScale)];
}
// 從當前context中創建一個改變大小后的圖片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
// 使當前的context出堆棧
UIGraphicsEndImageContext();
return newImage;
}
對圖片進行壓縮
#ifdef SD_WEBP
else if ([imageContentType isEqualToString:@"image/webp"])
{
image = [UIImage sd_imageWithWebPData:data];
}
#endif
else {
image = [[UIImage alloc] initWithData:data];
if (data.length/1024 > 128) {
image = [self compressImageWith:image];
}
UIImageOrientation orientation = [self sd_imageOrientationFromImageData:data];
if (orientation != UIImageOrientationUp) {
image = [UIImage imageWithCGImage:image.CGImage
scale:image.scale
orientation:orientation];
}
到了這里還需要進行最后一步。就是在SDWebImageDownloaderOperation的connectionDidFinishLoading方法里面的:
UIImage *image = [UIImage sd_imageWithData:self.imageData];
//將等比壓縮過的image在賦在轉成data賦給self.imageData
NSData *data = UIImageJPEGRepresentation(image, 1);
self.imageData = [NSMutableData dataWithData:data];
// 再配合
[[SDImageCache sharedImageCache] setValue:nil forKey:@"memCache"];