iOS分享世界

iOS端支持WebP格式图片的显示及NSData、UIImage

2017-01-18  本文已影响1406人  翻炒吧蛋滚饭

说说WebP

WebP说白了就是一种新的图片格式(其实也推出好久了),由谷歌研发,在安卓上的支持也蛮好的,从安卓4.0开始就已经原生支持了,但在iOS系统上,还是需要我们做些特殊处理的。关于WebP的种种好处和不好处,我就不细说了,看看一些关于WebP的介绍文章就行 https://isux.tencent.com/introduction-of-webp.html ,然后谷歌最近又在捅咕新的幺蛾子 http://www.elecfans.com/rengongzhineng/475356.html

我们需要做什么

主要是两大点:
  1、WebP图片的下载及展示
  2、UIWebView中展示WebP图片

图片的下载及展示

首先说一下图片的展示,在iOS项目中最常用的图片加载库,肯定是SDWebImage,如何让SDWebImage支持WebP格式的图片的加载呢?很简单:
  1、首先在项目设置中加入SDWebImage支持WebP的宏 SD_WEBP=1 :

Paste_Image.png
  2、这个宏就是告诉让SDWebImage支持WebP图片加载的宏,但是,如果你的SDWebImage是在CocoaPods中集成的,那么不好意思,项目中的宏在CocoaPods中是不生效的,所以我们,将CocoaPods中的SDWebImage移除,然后,直接将SDWebImage拖到项目中,这里需要注意的是,你在Git上的SDWebImage项目,里面一定要包含了UIImage+WebP这个分类。
Paste_Image.png
  以上,SDWebImage就支持WebP图片的加载了。
  当然,如果我们是自己处理的一些图片加载呢?比如[UIImage imageWithData:[NSData dataWithContentOfUrl:@"www.www.com.cn"]]这种呢,这种我们下载下来的NSData所构成的图片格式,就是WebP的了,想转换为UIIImage是没法的了,这里推荐一个比较好用的转换格式的库,YYImage,这个库默认不支持WebP,需要加入更多的组件,Pod集成如下:
pod 'YYImage'
pod 'YYImage/WebP'

这样,我们就可以将NSData正常转换为UIImage了,不管NSData里的数据是什么格式的:

YYImageDecoder *decoder = [YYImageDecoder decoderWithData:imageData scale:2.0];
UIImage *image = [decoder frameAtIndex:0 decodeForDisplay:YES].image;

再来说下UIWebView

UIWebView默认不支持WebP格式的图片加载,这里我们需要拦截图片的URL,这里我们可以使用NSURLProtocol进行拦截,但自己写还是比较麻烦的,这里推荐一个写好的:WebpForUIWebView
  用法:

Step 1: Drop [WEBPURLProtocol.h](https://github.com/8BADBEEF/WebpForUIWebView/blob/master/Webp/WEBPURLProtocol.h) and [WEBPURLProtocol.m](https://github.com/8BADBEEF/WebpForUIWebView/blob/master/Webp/WEBPURLProtocol.m) into your project, Swift or ObjC.
Step 2: If you didn't have a WebP decoder already in your project. Drop [WebP.framework](https://github.com/8BADBEEF/WebpForUIWebView/blob/master/WebP.framework), [UIImage+Webp.h](https://github.com/8BADBEEF/WebpForUIWebView/blob/master/Webp/UIImage%2BWebP.h),[UIImage+Webp.m](https://github.com/8BADBEEF/WebpForUIWebView/blob/master/Webp/UIImage%2BWebP.m), [WEBPDemoDecoder.h](https://github.com/8BADBEEF/WebpForUIWebView/blob/master/Webp/WEBPDemoDecoder.h), [WEBPDemoDecoder.m](https://github.com/8BADBEEF/WebpForUIWebView/blob/master/Webp/WEBPDemoDecoder.m) into your project. If you already have a WebP decoder in your project, create a new class that conforms to [WEBPURLProtocolDecoder](https://github.com/8BADBEEF/WebpForUIWebView/blob/master/Webp/WEBPURLProtocol.h#L5) using the existing decoder.
Step 3: Whenever you are in the mood for rendering WebP in UIWebView, start the engine with the following code:
[WEBPURLProtocol registerWebP:/*An instance of any class that conforms to WEBPURLProtocolDecoder*/];
All done.

以上,WebP的支持就OK了。

上一篇 下一篇

猜你喜欢

热点阅读