由于最近項目需求涉馁,需要將項目中圖片的加載做到同時兼容WebP格式,對于WebP格式的兼容族铆,主要分為兩大塊內(nèi)容:
- WebView中對WebP格式的加載
- 普通的圖片控件對于WebP格式的加載
經(jīng)測試揍拆,如果不做任何處理瓮增,iOS是不支持對WebP格式的原生支持的。對于WebP格式的圖片的加載也就需要經(jīng)過一些處理才能夠?qū)ζ溥M(jìn)行支持驻民。大致原理:將服務(wù)器返回的WebP格式圖片進(jìn)行處理轉(zhuǎn)換成控件所能識別的二進(jìn)制流致开,然后按照普通的圖片加載方式進(jìn)行加載。上傳給服務(wù)器的WebP格式的圖片也是相同的原理解孙。
好了坑填,對于以上兩種加載,iOS實現(xiàn)方式又是怎么樣的呢弛姜?
實際上脐瑰,SDWebImage中已經(jīng)支持了WebP格式的圖片,并且可以在UIImage與WebP之間進(jìn)行圖片的相互轉(zhuǎn)換廷臼,所以對于iOS端的WebP格式圖片的支持可以通過SDWebImage/WebP來支持處理苍在。
可以通過pod 'SDWebImage/WebP'
來進(jìn)行安裝绝页。
普通控件加載WebP格式圖片
在使用普通控件加載WebP格式圖片的時候,需要SDWebImage/WebP提供的UIImage+WebP分類來進(jìn)行WebP格式圖片的轉(zhuǎn)換:
+ (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;
如果直接在加載的時候?qū)ebP格式圖片進(jìn)行支持寂恬,可以通過如下方式進(jìn)行配置续誉,即可完成SDWebImage的WebP的支持。
步驟如下:
1.工程引入SDWebImage開源庫初肉;
2.引入WebP.framework,下載地址:https://github.com/seanooi/iOS-WebP屈芜。
3.讓SDWebImage支持WebP,設(shè)置如下Build Settings -- Preprocessor Macros , add SD_WEBP=1朴译。
這里需要注意的一點:如果按照配置發(fā)現(xiàn)還是不能夠正常加載的話井佑,可能是因為cocopods中的SDWebImage未能找到WebP.framework所致,此時可以將cocopods中的SDWebImage拿出來眠寿,應(yīng)該就能夠正常加載了躬翁。
webView對WebP格式的支持
webView對WebP格式圖片的加載可以通過截獲對應(yīng)的圖片地址來進(jìn)行。具體實現(xiàn)可以使用NSURLProtocol 來進(jìn)行UIWebVIew的網(wǎng)絡(luò)請求判斷盯拱,如果請求的內(nèi)容是WebP格式的圖片盒发,那么對WebP格式圖片進(jìn)行轉(zhuǎn)碼緩存之后再進(jìn)行圖片的加載具體代碼如下:
#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