WebP 是 Google 推出的圖片格式,相比 JPG、PNG 有明顯優勢:在同等畫質下檔案更小。對於電商這類圖片密集的 App,全面改用 WebP 能省下可觀的流量與儲存。
目前 iOS 並不原生支援 WebP,直接拿到網路資料也無法顯示,必須先解碼成 UIImage 才能上屏。
在 Podfile 中加入:
pod 'SDWebImage/WebP'
這會替 SDWebImage 加上 UIImage 的 WebP category,同時引入 libwebp。載入圖片時它會判斷格式,若為 WebP 就呼叫 Google 的 libwebp 解碼。呼叫鏈大致如下:
sd_setImageWithURL → URLSession:task:didCompleteWithError: → sd_imageWithData → sd_imageWithWebPData // 成功後回傳 UIImage
如果網頁裡也用了 WebP,光靠上面那招是不夠的——UIWebView/WKWebView 自己不會解碼。可行的做法是自訂 NSURLProtocol 並註冊,攔下請求自行處理。關鍵程式碼如下:
- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(nullable NSError *)error {
if (error == nil) {
if ([task.currentRequest.URL.absoluteString hasSuffix:@"webp"]) {
UIImage *image = [UIImage sd_imageWithData:self.imageData];
NSData *transData = UIImageJPEGRepresentation(image, 0.8f);
self.beginAppendData = NO;
self.imageData = nil;
[self.client URLProtocol:self didLoadData:transData];
}
[self.client URLProtocolDidFinishLoading:self];
} else if ([[error domain] isEqual:NSURLErrorDomain]
&& [error code] == NSURLErrorCancelled) {
[self.client URLProtocol:self didFailWithError:error];
} else {
[[self client] URLProtocol:self didFailWithError:error];
}
}在請求完成時判斷 URL 是否以 webp 結尾:若是,就用 SDWebImage 解碼轉檔,然後把 beginAppendData 置為 NO、imageData 清空,再重新讓 client 載入這批資料。
為什麼需要 beginAppendData 這個旗標?因為一個圖片請求的資料往往分多次送達:
- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data {
if ([dataTask.currentRequest.URL.absoluteString hasSuffix:@"webp"]) {
self.beginAppendData = YES;
[self.imageData appendData:data]; // 先累積,不對外觸發
}
if (!_beginAppendData) {
[self.client URLProtocol:self didLoadData:data];
}
}遇到 webp 時先把每批資料 append 起來、暫時不通知 client,等整個請求完成後統一解碼再一次性送出。
自訂 URL Protocol 時,一定要實作重定向的回呼,否則在 WebView 中會出問題:
- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
willPerformHTTPRedirection:(NSHTTPURLResponse *)response
newRequest:(NSURLRequest *)newRequest
completionHandler:(void (^)(NSURLRequest *))completionHandler {
NSMutableURLRequest *redirectRequest = [newRequest mutableCopy];
[[self class] removePropertyForKey:URLProtocolHandledKey inRequest:redirectRequest];
[[self client] URLProtocol:self
wasRedirectedToRequest:redirectRequest
redirectResponse:response];
[self.session invalidateAndCancel];
[[self client] URLProtocol:self
didFailWithError:[NSError errorWithDomain:NSCocoaErrorDomain
code:NSUserCancelledError
userInfo:nil]];
}在 AppDelegate 的 didFinishLaunchingWithOptions 中註冊即可:
[NSURLProtocol registerClass:[DMCustomURLSessionProtocol class]];
Demo 專案、WebP 測試圖片與含 WebP 的網頁範例,可從文中連結取得。