首页 IT正文

iOS加载WebP格式图片小结

admin IT 2018-11-11 878 0

由于最近项目需求,需要将项目中图片的加载做到同时兼容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 <Foundation/Foundation.h>@class UIImage;@protocol WEBPURLProtocolDecoder<NSObject>- (UIImage *)decodeWebpData: (NSData *)data;@end@interface WEBPURLProtocol : NSURLProtocol+ (void)registerWebP: (id <WEBPURLProtocolDecoder>)externalDecoder;
+ (void)unregister;@end
#import <objc/message.h>#import <UIKit/UIKit.h>#import "WEBPURLProtocol.h"#define UIWEBVIEW_WEBP_DEBUGstatic 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格式图片小结
本文链接:https://xl.cndyun.com/post/371.html
作者授权:除特别说明外,本文由 admin 原创编译并授权 小龙的博客 刊载发布。
版权声明:本文不使用任何协议授权,您可以任何形式自由转载或使用。
«    2024年3月    »
123
45678910
11121314151617
18192021222324
25262728293031

分享:

支付宝

微信