實(shí)現(xiàn)方案來自度娘
1.在SDWebImage目錄下的 UIImage+MultiFormat.m 文件中增加方法
+ (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;
// 創(chuàng)建一個(gè)bitmap的context
// 并把它設(shè)置成為當(dāng)前正在使用的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)];
}
// 從當(dāng)前context中創(chuàng)建一個(gè)改變大小后的圖片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
// 使當(dāng)前的context出堆棧
UIGraphicsEndImageContext();
return newImage;
}
2.在該文件下面方法中調(diào)用
+ (nullable UIImage *)sd_imageWithData:(nullable NSData *)data {
if (!data) { return nil; }
UIImage *image;
SDImageFormat imageFormat = [NSData sd_imageFormatForImageData:data];
if (imageFormat == SDImageFormatGIF) {
image = [UIImage sd_animatedGIFWithData:data];
}
#ifdef SD_WEBP
else if (imageFormat == SDImageFormatWebP) {
image = [UIImage sd_imageWithWebPData:data];
}
#endif
else {
image = [[UIImage alloc] initWithData:data];
//在這里增加下面三行代碼
if (data.length/1024 > 128) {
image = [self compressImageWith:image];
}
#if SD_UIKIT || SD_WATCH
UIImageOrientation orientation = [self sd_imageOrientationFromImageData:data];
if (orientation != UIImageOrientationUp) {
image = [UIImage imageWithCGImage:image.CGImage
scale:image.scale orientation:orientation];
}
#endif
}
return image;
}