iOS載入WebP格式圖片小結

weixin_34124651發表於2017-01-14

由於最近專案需求,需要將專案中圖片的載入做到同時相容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。

1611317-a9be9918498dc685.png
修改配置

這裡需要注意的一點:如果按照配置發現還是不能夠正常載入的話,可能是因為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_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

相關文章