现在大多数应用程序都使用图片来增强用户体验,我注意到的一个问题是加载图片所需的时间。 (并不是每个人都拥有快速连接的奢侈)
Google 的 WebP 图片格式相比 PNG 或 JPEG 可提供更好的压缩,允许应用程序以更小的文件大小发送/检索图片,减少请求时间,并希望提供更好的用户体验。
将 iOS-WebP
文件夹内的3个文件包含到您的项目中
UIImage+WebP.h
UIImage+WebP.m
WebP.framework
如果您使用的是 Cocoapods,不要忘了 #import "UIImage+WebP.h"
或 #import <UIImage+WebP.h>
。在 iOS-WebP
中有3个方法:将图片转换为 WebP 格式、将图片从 WebP 格式转换,以及设置图片的透明度。
+ (void)imageToWebP:(UIImage *)image quality:(CGFloat)quality alpha:(CGFloat)alpha preset:(WebPPreset)preset
completionBlock:(void (^)(NSData *result))completionBlock
failureBlock:(void (^)(NSError *error))failureBlock;
+ (void)imageWithWebP:(NSString *)filePath
completionBlock:(void (^)(UIImage *result))completionBlock
failureBlock:(void (^)(NSError *error))failureBlock;
- (UIImage *)imageByApplyingAlpha:(CGFloat)alpha;
图像的编码和解码在网络线程中进行,和结果在主线程的完成块中返回,以避免锁定主线程,允许按需更新 UI。
// quality value is [0, 100]
// alpha value is [0, 1]
[UIImage imageToWebP:[UIImage imageNamed:@"demo.jpg"] quality:quality alpha:alpha preset:WEBP_PRESET_DEFAULT completionBlock:^(NSData *result) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *webPPath = [paths[0] stringByAppendingPathComponent:@"image.webp"];
if (![result writeToFile:webPPath atomically:YES]) {
NSLog(@"Failed to save file");
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error.localizedDescription);
}];
WebPPreset
可能的值WEBP_PRESET_DEFAULT
(默认预设)WEBP_PRESET_PICTURE
(数字图片,如肖像、内景)WEBP_PRESET_PHOTO
(室外照片,有自然光线)WEBP_PRESET_DRAWING
(手绘或线条绘图,细节对比度高)WEBP_PRESET_ICON
(小型彩色图像)WEBP_PRESET_TEXT
(类似文本的)如果您需要调整编码算法的性能,可以配置块中指定预设的覆盖。
// quality value is [0, 100]
// alpha value is [0, 1]
[UIImage imageToWebP:[UIImage imageNamed:@"demo.jpg"] quality:quality alpha:alpha
preset:WEBP_PRESET_DEFAULT
config:^(WebPConfig *config) {
config->sns_strength = 50.0f;
config->filter_strength = 0.0f;
config->method = 2;
config->preprocessing = 0;
config->filter_sharpness = 0;
config->thread_level = 1;
}
completionBlock:^(NSData *result) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *webPPath = [paths[0] stringByAppendingPathComponent:@"image.webp"];
if (![result writeToFile:webPPath atomically:YES]) {
NSLog(@"Failed to save file");
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error.localizedDescription);
}];
所有可能的配置值可以在 WebPConfig 结构中的 encode.h 中找到。
[UIImage imageWithWebP:@"/path/to/file" completionBlock:^(UIImage *result) {
UIImageView *myImageView = [[UIImageView alloc] initWithImage:result];
}failureBlock:^(NSError *error) {
NSLog(@"%@", error.localizedDescription);
}];
//alpha value is [0, 1]
UIImage *transparencyImage = [[UIImage imageNamed:image.jpg] imageByApplyingAlpha:0.5];
imageByApplyingAlpha:alpha
函数由 shmidt 捐赠WebPConfig
块由 weibel 和 escherba 捐赠