You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将CGImage保存为WebP格式时出现unsupported file format错误如何解决

错误根因

你遇到的unsupported file format 'org.webmproject.webp'错误核心原因是 iOS 17以下、macOS 14以下的系统原生ImageIO框架仅支持WebP格式解码,不支持WebP格式编码,所以调用CGImageDestinationCreateWithURL传入UTType.webP.identifier时会创建失败。


解决方案

方案1:适配系统原生支持(仅支持iOS17+/macOS14+)

如果你的App最低部署版本可以升到iOS17/macOS14及以上,直接加系统版本判断即可使用原生编码能力,无需引入第三方依赖:

// 先导入依赖框架
import UniformTypeIdentifiers

// 在创建目标存储对象前增加版本判断
if #available(iOS 17.0, macOS 14.0, *) {
    guard let destination = CGImageDestinationCreateWithURL(destUrl as CFURL, UTType.webP.identifier, 1, nil) else { 
        return 
    }
    // 可自定义WebP压缩参数
    let options: [CFString: Any] = [
        kCGImageDestinationLossyCompressionQuality: 0.8 // 取值0-1,1为无损压缩
    ]
    CGImageDestinationAddImage(destination, image!, options as CFDictionary)
    guard CGImageDestinationFinalize(destination) else {
        print("WebP编码写入失败")
        return
    }
} else {
    // 低版本系统走第三方编码逻辑
}

方案2:兼容低版本系统,引入第三方编码库

如果需要覆盖iOS17以下的用户,推荐使用封装了libwebp的成熟第三方组件实现编码,以SDWebImageWebPCoder为例:

  1. 集成依赖:通过CocoaPods引入pod 'SDWebImageWebPCoder'
  2. 初始化注册编码器:
import SDWebImageWebPCoder

// App启动时注册全局WebP编码器
SDImageCodersManager.shared.addCoder(SDImageWebPCoder.shared)
  1. 替换原有保存逻辑:
guard let targetCGImage = image else { return }
// 编码生成WebP数据,可自定义压缩质量
guard let webpData = SDImageWebPCoder.shared.encodedData(
    with: targetCGImage,
    format: .webP,
    options: [.encodeQuality: 0.8]
) else {
    return
}
// 写入到目标路径
do {
    try webpData.write(to: destUrl)
} catch {
    print("WebP写入失败:\(error.localizedDescription)")
}

内容的提问来源于stack exchange,提问作者Cheok Yan Cheng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 01:27:00