iOS加载WebP格式图片小结

作者: a_只羊 | 来源:发表于2017-01-14 20:20 被阅读1790次

由于最近项目需求,需要将项目中图片的加载做到同时兼容WebP格式,对于WebP格式的兼容,主要分为两大块内容:

  • WebView中对WebP格式的加载
  • 普通的图片控件对于WebP格式的加载

经测试,如果不做任何处理,iOS是不支持对WebP格式的原生支持的。对于WebP格式的图片的加载也就需要经过一些处理才能够对其进行支持。大致原理:将服务器返回的WebP格式图片进行处理转换成控件所能识别的二进制流,然后按照普通的图片加载方式进行加载。上传给服务器的WebP格式的图片也是相同的原理。

好了,对于以上两种加载,iOS实现方式又是怎么样的呢?
实际上,SDWebImage中已经支持了WebP格式的图片,并且可以在UIImage与WebP之间进行图片的相互转换,所以对于iOS端的WebP格式图片的支持可以通过SDWebImage/WebP来支持处理。
可以通过pod 'SDWebImage/WebP'来进行安装。

普通控件加载WebP格式图片

在使用普通控件加载WebP格式图片的时候,需要SDWebImage/WebP提供的UIImage+WebP分类来进行WebP格式图片的转换:

+ (UIImage *)sd_imageWithWebPData:(NSData *)data;

在Native中使用WebP格式图片的方法

NSString *path = [[NSBundle mainBundle] pathForResource:@"logo" ofType:@"webp"];
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
UIImage *img = [UIImage sd_imageWithWebPData:data];self.imageView.image = img;

如果直接在加载的时候对WebP格式图片进行支持,可以通过如下方式进行配置,即可完成SDWebImage的WebP的支持。

步骤如下:
1.工程引入SDWebImage开源库;
2.引入WebP.framework,下载地址:https://github.com/seanooi/iOS-WebP
3.让SDWebImage支持WebP,设置如下Build Settings -- Preprocessor Macros , add SD_WEBP=1。

修改配置

这里需要注意的一点:如果按照配置发现还是不能够正常加载的话,可能是因为cocopods中的SDWebImage未能找到WebP.framework所致,此时可以将cocopods中的SDWebImage拿出来,应该就能够正常加载了。

webView对WebP格式的支持

webView对WebP格式图片的加载可以通过截获对应的图片地址来进行。具体实现可以使用NSURLProtocol 来进行UIWebVIew的网络请求判断,如果请求的内容是WebP格式的图片,那么对WebP格式图片进行转码缓存之后再进行图片的加载具体代码如下:

#import <objc/message.h>
#import <UIKit/UIKit.h>
#import "WEBPURLProtocol.h"
#define UIWEBVIEW_WEBP_DEBUG

static NSString * const WebpURLRequestHandledKey = @"Webp-handled";
static NSString * const WebpURLRequestHandledValue = @"handled";
static id <WEBPURLProtocolDecoder> decoder = nil;

@interface WEBPURLProtocol () <NSURLSessionDataDelegate>
@property (atomic, copy) NSArray *modes;
@property (atomic, strong) NSThread *clientThread;
@property (atomic, strong) NSMutableData *data;
@property (atomic, strong) NSURLRequest *tmpRequest;
@property (atomic, strong) NSURLSession *session;
@end

@implementation WEBPURLProtocol

- (void)p_performBlock:(dispatch_block_t)block
{
#if defined (DEBUG) && defined (UIWEBVIEW_WEBP_DEBUG)
    NSAssert(self.modes != nil, @"UIWEBVIEW WEBP ERROR #4");
    NSAssert(self.modes.count > 0, @"UIWEBVIEW WEBP ERROR #5");
    NSAssert(self.clientThread != nil, @"UIWEBVIEW WEBP ERROR #6");
#endif
    [self performSelector:@selector(p_helperPerformBlockOnClientThread:) onThread:self.clientThread withObject:[block copy] waitUntilDone:NO modes:self.modes];
}

- (void)p_helperPerformBlockOnClientThread:(dispatch_block_t)block
{
#if defined (DEBUG) && defined (UIWEBVIEW_WEBP_DEBUG)
    NSAssert([NSThread currentThread] == self.clientThread, @"UIWEBVIEW WEBP ERROR #7");
#endif
    if(block != nil)
    {
        block();
    }
}

+ (void)registerWebP: (id <WEBPURLProtocolDecoder>)externalDecoder {
#if defined (DEBUG) && defined (UIWEBVIEW_WEBP_DEBUG)
 NSAssert([NSThread isMainThread], @"UIWEBVIEW WEBP ERROR #8");
    NSAssert(externalDecoder != nil, @"UIWEBVIEW WEBP ERROR #10");
    NSAssert([externalDecoder respondsToSelector:@selector(decodeWebpData:)], @"UIWEBVIEW WEBP ERROR #12");
#endif
    decoder = externalDecoder;
 [NSURLProtocol registerClass:self];
}

+ (void)unregister {
#if defined (DEBUG) && defined (UIWEBVIEW_WEBP_DEBUG)
    NSAssert([NSThread isMainThread], @"UIWEBVIEW WEBP ERROR #9");
#endif
 [self unregisterClass:self];
}

+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
    
    if (!request) {
        return NO;
    }
    
    if (!request.URL) {
        return NO;
    }
    
    if (!request.URL.absoluteString) {
        return NO;
    }
    
    NSString * const requestURLPathExtension = request.URL.pathExtension.lowercaseString;

    if (!requestURLPathExtension) {
        return NO;
    }
    
    BOOL webpExtension = NO;
    
    if ([@"webp" isEqualToString:requestURLPathExtension]) {
        webpExtension = YES;
    }
    
    if (webpExtension == NO) {
        return NO;
    }
    
    if ([self propertyForKey:WebpURLRequestHandledKey inRequest:request] == WebpURLRequestHandledValue) {
        return NO;
    }
    
    NSString *scheme = request.URL.scheme;
    
    if (!scheme) {
        return NO;
    }
    
    scheme = [scheme lowercaseString];
    
    if (!scheme) {
        return NO;
    }
    
    if (([@"http" isEqualToString:scheme] == NO) && ([@"https" isEqualToString:scheme] == NO)) {
        return NO;
    }
    
 request = [self webp_canonicalRequestForRequest:request];
 return [NSURLConnection canHandleRequest:request];
}

+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
 return [self webp_canonicalRequestForRequest:request];
}

+ (NSURLRequest *)webp_canonicalRequestForRequest:(NSURLRequest *)request {
 NSURL *url = request.URL;
 NSMutableURLRequest * const modifiedRequest = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:request.cachePolicy timeoutInterval:request.timeoutInterval];
    NSString *mimeType = @"image/webp";
 [modifiedRequest addValue:mimeType forHTTPHeaderField:@"Accept"];
 [self setProperty:WebpURLRequestHandledValue forKey:WebpURLRequestHandledKey inRequest:modifiedRequest];
 return modifiedRequest;
}

- (id)initWithRequest:(NSURLRequest *)request cachedResponse:(NSCachedURLResponse *)cachedResponse client:(id<NSURLProtocolClient>)client {
 if ((self = [super initWithRequest:request cachedResponse:cachedResponse client:client])) {
  request = [self.class canonicalRequestForRequest:request];
        self.tmpRequest = request;
 }
 return self;
}

- (void)dealloc {
    [self.session invalidateAndCancel];
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
    NSHTTPURLResponse * const httpResponse = [response isKindOfClass:[NSHTTPURLResponse class]] ? (NSHTTPURLResponse *)response : nil;
    
    if (httpResponse.statusCode != 200) {
        completionHandler(NSURLSessionResponseCancel);
        [self p_performBlock:^{
            [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed];
        }];
        return;
    }
    
    completionHandler(NSURLSessionResponseAllow);
    [self p_didReceiveResponsefromCache:NO expectedLength:response.expectedContentLength];
}

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
   didReceiveData:(NSData *)data {
    [self.data appendData:data];
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error {
    if (error) {
        [self p_performBlock:^{
            [self.client URLProtocol:self didFailWithError:error];
        }];
    }
    else {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSError *error = [NSError errorWithDomain:@"Webp_UIWebView_ERROR_DOMAIN" code:1 userInfo:@{}];
            UIImage *image = [decoder decodeWebpData:self.data];
            if (!image) {
                [self p_performBlock:^{
                    [self.client URLProtocol:self didFailWithError:error];
                }];
                return;
            }
            NSData *imagePngData = UIImagePNGRepresentation(image);
            [self p_performBlock:^{
                [self.client URLProtocol:self didLoadData:imagePngData];
                [self.client URLProtocolDidFinishLoading:self];
            }];
        });
    }
}

- (void)p_startConnection {
    [self p_performBlock:^{
        self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
        NSURLSessionDataTask *task = [self.session dataTaskWithRequest:self.tmpRequest];
        [task resume];
    }];
}

- (void)startLoading {
    NSMutableArray *calculatedModes;
    NSString *currentMode;
    calculatedModes = [NSMutableArray array];
    [calculatedModes addObject:NSDefaultRunLoopMode];
    currentMode = [[NSRunLoop currentRunLoop] currentMode];
    if ( (currentMode != nil) && ! [currentMode isEqual:NSDefaultRunLoopMode] ) {
        [calculatedModes addObject:currentMode];
    }
    self.modes = calculatedModes;
#if defined (DEBUG) && defined (UIWEBVIEW_WEBP_DEBUG)
    NSAssert([self.modes count] > 0, @"UIWEBVIEW WEBP ERROR #11");
#endif
    self.clientThread = [NSThread currentThread];
    [self p_startConnection];
}

- (void)stopLoading {
    [self.session invalidateAndCancel];
}

- (void)p_didReceiveResponsefromCache: (BOOL)fromCache expectedLength: (long long)expectedLength{
    NSString *contentType = @"image/png";
    NSDictionary * const responseHeaderFields = @{
                                                  @"Content-Type": contentType,
                                                  @"X-Webp": @"YES",
                                                  };
    
    NSURLRequest * const request = self.request;
    NSHTTPURLResponse * const modifiedResponse = [[NSHTTPURLResponse alloc] initWithURL:request.URL statusCode:200 HTTPVersion:@"1.0" headerFields:responseHeaderFields];
    
    if (!fromCache) {
        if (expectedLength > 0) {
            self.data = [[NSMutableData alloc] initWithCapacity:expectedLength];
        } else {
            self.data = [[NSMutableData alloc] initWithCapacity:50 * 1024];// Default to 50KB
        }
    }
    [self p_performBlock:^{
        [self.client URLProtocol:self didReceiveResponse:modifiedResponse cacheStoragePolicy:NSURLCacheStorageAllowed];
    }];
}

@end

使用WebURLProtocol前需要提前注册,通常在AppDelegate中 **- (BOOL)application:(UIApplication )application didFinishLaunchingWithOptions:(nullable NSDictionary )launchOptions;中就行注册。

注册例子如下:

[NSURLProtocol registerClass:[WEBPURLProtocol class]];

这样做的好处就是不影响webView其他功能代码下,添加了对WebP格式图片的支持。

参考:
http://blog.devzeng.com/blog/ios-webp-usage.html
https://isux.tencent.com/introduction-of-webp.html
http://blog.csdn.net/shenjx1225/article/details/47259701

相关文章

  • iOS - .webp图片显示

    WebP格式,谷歌(google)开发的一种旨在加快图片加载速度的图片格式。 在iOS中会出现加载webp图片显示...

  • iOS 加载webp格式的图片

    苹果原生不支持加载webp格式的图片。 加载网络图片为webp格式的建议使用SDWebImage,它应该iOS开发...

  • iOS加载WebP格式图片小结

    由于最近项目需求,需要将项目中图片的加载做到同时兼容WebP格式,对于WebP格式的兼容,主要分为两大块内容: W...

  • ios解决.webp格式图片不能正常显示的问题

    由于最近项目的需求,图片的加载需要对webp格式的图片做兼容,但是ios是不支持webp格式的原生支持的,对于we...

  • iOS 加载webp格式的图片 pod "SDWebImage

    SDWebImage 应该iOS开发中最常用的图片框架之一,用于加载网络图片。 但是如果图片的格式是webp的格式...

  • web 前端的一些知识

    webp 图片格式WebP格式,谷歌(google)开发的一种旨在加快图片加载速度的图片格式。图片压缩体积大约只有...

  • Android 图片资源大瘦身

    Android 图片推荐使用WebP格式的图片 WebP格式,谷歌(google)开发的一种旨在加快图片加载速度的...

  • iOS 加载webP格式图片

    前阵子遇到一个加载图片的问题,webP格式图片如何在iOS技术上显示图片呢?小编当时也是头疼,想了好几个办法都行不...

  • [iOS]Native应对WebP使用的解决方案

    一、WebP是什么? WebP格式,谷歌(google)开发的一种旨在加快图片加载速度的图片格式。图片压缩体积大约...

  • pod 'libwebp'失败的解决办法

    在使用SDWebImage加载webp格式图片时,需要引入库SDWebImage/WebP。 Podfile 文件...

网友评论

  • APP福星高照:WEBPURLProtocolDecoder类哪来的?
    a_只羊:这个是自己定义的protocol,用于声明转换webP 格式图片的方法 - (UIImage *)decodeWebpData: (NSData *)data; ,稍等,我更新一下文章
  • 97f52a50453b:我想问一下,上传的时候如何把别的格式的图片转成webp格式呢
  • 白雪天枫:我自己刚刚解决这个问题用的是yy解决iOS显示问题,以及web显示webP格式问题
    可参考https://www.jianshu.com/p/1a96b54486fc
  • LByy:你好,你这个webp格式的图片 有用imageview加载服务器上的webp格式的图片没啊?sdwebimage里面没有直接处理服务器上webp格式图片方法吧

本文标题:iOS加载WebP格式图片小结

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