您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 使用 WebP 圖片格式:轉換、壓縮與體積比較

編輯:iOS 開發綜合

WebP 是 Google 推出的圖片格式,在同樣畫質下檔案體積明顯小於 PNG 與 JPEG,對 App 的安裝包大小與網路載入速度都有幫助。以下示範在 iOS 中如何把 PNG 轉成 WebP 並讀回顯示。

導入標頭

#import "UIImage+WebP.h"

完整範例:PNG 與 WebP 體積對照

#import "ViewController.h"
#import "UIImage+WebP.h"

@interface ViewController ()
@property (nonatomic, strong) UIImageView *webPImageView;
@property (nonatomic, strong) UILabel *webPLabel1;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 讀取原始 PNG 並顯示
    NSString *normalImg = [[NSBundle mainBundle] pathForResource:@"changmen1" ofType:@"png"];
    uint64_t fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:normalImg error:nil] fileSize];

    UIImage *demoImage = [UIImage imageNamed:@"changmen1.png"];
    UIImageView *pngView = [[UIImageView alloc] initWithImage:demoImage];
    pngView.frame = CGRectMake(0, 0, demoImage.size.width, demoImage.size.height);
    [self.view addSubview:pngView];

    UILabel *pngLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(pngView.frame) + 5, 300, 10)];
    pngLabel.text = [NSString stringWithFormat:@"%@ format file size: %.2f KB",
                     [[normalImg pathExtension] uppercaseString], (double)fileSize / 1024];
    [pngLabel setFont:[UIFont systemFontOfSize:12]];
    [self.view addSubview:pngLabel];

    // 準備顯示轉檔後的 WebP
    _webPImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(pngView.frame) + 20,
                                                  demoImage.size.width, demoImage.size.height)];
    [self.view addSubview:_webPImageView];

    _webPLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_webPImageView.frame) + 5, 300, 10)];
    [_webPLabel1 setFont:[UIFont systemFontOfSize:12]];
    [self.view addSubview:_webPLabel1];

    // 把 UIImage 編碼成 WebP 資料
    [UIImage imageToWebP:demoImage
                 quality:75.0
                   alpha:1.0
                  preset:WEBP_PRESET_PHOTO
         completionBlock:^(NSData *result) {
        [self displayImageWithData:result];
    } failureBlock:^(NSError *error) {
        NSLog(@"WebP 編碼失敗:%@", error);
    }];
}

- (void)displayImageWithData:(NSData *)webPData {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *webPPath = [paths[0] stringByAppendingPathComponent:@"image.webp"];

    if ([webPData writeToFile:webPPath atomically:YES]) {
        [UIImage imageWithWebP:webPPath completionBlock:^(UIImage *result) {
            uint64_t fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:webPPath error:nil] fileSize];
            _webPLabel1.text = [NSString stringWithFormat:@"%@ format file size: %.2f KB",
                                [[webPPath pathExtension] uppercaseString], (double)fileSize / 1024];
            [_webPImageView setImage:result];
        } failureBlock:^(NSError *error) {
            NSLog(@"WebP 解碼失敗:%@", error);
        }];
    }
}

@end

效果

從上圖可以清楚看到,同一張圖轉成 WebP 後體積有明顯下降,而畫面上幾乎看不出差異。

幾個實務上的重點

quality 與 preset 怎麼選。quality 越低壓縮越狠,0.75 通常是畫質與體積的甜蜜點。preset 會依用途調整編碼策略:WEBP_PRESET_PHOTO 適合照片、WEBP_PRESET_PICTURE 適合一般圖、WEBP_PRESET_ICON 適合小圖示、WEBP_PRESET_TEXT 適合含文字的手繪圖。選錯 preset 會讓體積反而變大。

alpha 參數。WebP 支援透明通道,alpha 設為 1.0 表示保留。若原圖沒有透明需求,關掉它可以再省一點空間。

iOS 原生不支援 WebP。上述 UIImage+WebP 是第三方分類(category),並非系統 API。使用第三方編解碼庫要注意授權條款(libwebp 為 BSD 授權,通常可商用,但仍需保留版權聲明),並確認其與你的部署目標相容。

何時該用 WebP。App 內建資源建議仍以 PNG(需透明)或 PDF asset catalog 為主,因為 iOS 會針對裝置做圖形編譯與最佳化;WebP 真正的效益在網路下載的圖片——例如伺服器端的商品圖、頭像、動態內容。這時搭配 SDWebImage 或 Kingfisher 等支援 WebP 的框架,就能在保持畫質的同時顯著降低流量。

別忘了 CDN 端的格式協商。更省事的做法是在伺服器或 CDN 上依 User-Agent 自動回傳 WebP,並保留原格式作為後備,這樣客户端不需要額外引入解碼庫,也能達到同樣效果。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved