iOS 加载 webp 格式的图片

8,468 阅读1分钟

能进来看这篇文章的同学, 相信已经不是新手了, 所以基本的东西就不多说了.

本文主要说的是使用 SDWebImage 以不同的方式加载 webp 格式的图片, webp 格式图片的优点 与 缺点我也不多说了, 最明显就是相同清晰度质量比其他格式体积小, 具体的大家自己百度吧.

1. 导入三方库

通过cocoapods 导入相关的库, podfile 如下代码 导入 SDWebImageWebPCoder 时会自动导入 libwebp, 所以最终会有三个库, 分别是 SDWebImage, SDWebImageWebPCoder , libwebp .

pod 'SDWebImage'
pod 'SDWebImageWebPCoder'

2. 图片资源

我们找一张 webp 格式的图片资源放到根目录, 注意不是放到 Assets.xcassets 文件夹, 另外请我们的运维同事放了一张到服务端, 让我可以通过局域网访问.

image.png

3. 初始化webp解码库

#import <SDImageWebPCoder.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [self setupWebPCoder];
    
    return YES;
}

- (void)setupWebPCoder {
    SDImageWebPCoder *webPCoder = [SDImageWebPCoder sharedCoder];
    [[SDImageCodersManager sharedManager] addCoder:webPCoder];
    
    [[SDWebImageDownloader sharedDownloader] setValue:@"image/webp,image/*,*/*;q=0.8" forHTTPHeaderField:@"Accept"];
}

@end

4. 加载 UIImageView 视图

#import "ViewController.h"
#import <SDWebImageWebPCoder.h>

@interface ViewController ()

@property(nonatomic, strong) UIImageView *imageView;
 
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    
    // 网络 url 链接加载网络图片
    [self loadURLImage];
    // 获取本地文件资源解压成图片
//    [self loadLocalImage];
    // 本地 url 链接加载本地图片
//    [self loadLocalURLImage];
   
}

- (void)setupUI {
    
    _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 100, 282, 212)];
    [self.view addSubview:_imageView];
}

@end

5. 三种加载本地图片方式

1. 加载网络图片
- (void)loadURLImage {
    NSString *urlString = @"http://192.168.2.44/webp_image.webp";
    NSURL *imgUrl = [NSURL URLWithString:urlString];
    [_imageView sd_setImageWithURL:imgUrl];
}
2. 加载本地资源文件
- (void)loadLocalImage {
    NSString *imgName = @"webp_image";
    NSString *imgType = @"webp";
    NSString *path = [[NSBundle mainBundle] pathForResource:imgName ofType:imgType];
    NSData *webpData = [NSData dataWithContentsOfFile: path];
    UIImage *image = [[SDImageWebPCoder sharedCoder] decodedImageWithData:webpData options:nil];
    _imageView.image = image;
}
3. 加载本地 url 链接
- (void)loadLocalURLImage{
    NSString *imgName = @"webp_image";
    NSString *imgType = @"webp";
    NSString *path = [[NSBundle mainBundle] pathForResource:imgName ofType:imgType];
    NSURL *imgUrl = [NSURL fileURLWithPath:path];
    [_imageView sd_setImageWithURL:imgUrl];
}