iOS 經常使用圖片格式判斷 (Swift)

經常使用的圖片格式有一下幾種。html

  • PNG
  • JPEG
  • GIF
  • WebP 是 Google 製造的一個圖片格式,針對網絡上快速傳輸就好了優化
  • TIFF/TIF 在數字影響、遙感、醫學等領域中獲得了普遍的應用。TIFF文件的後綴是.tif或者.tiff
  • HEIC iOS11 後,蘋果拍照圖片的默認格式
  • HEIF 用於存儲動態圖像

那麼,怎麼去判斷。一般圖片格式都會存儲圖片的 Hex Signature 中(十六進制簽名) 相信地址能夠參考:www.garykessler.net/library/fil…web

JPGE 二進制數據前兩個字節數據爲
Hex Signature
FF D8
複製代碼
PNG
Hex Signature
89 50 4E 47 0D 0A 1A 0A
複製代碼
GIF
Hex Signature
47 49 46 38 37 61 or
47 49 46 38 39 61
複製代碼
TIFF
Hex Signature
49 20 49 or
49 49 2A 00 or
4D 4D 00 2B or
4D 4D 00 2A
複製代碼
HEIC
Hex Signature
00
複製代碼

HEIF
Hex Signature
00
複製代碼

網上不少都是複製過來的,都知道代碼是怎樣的。可是不知道爲啥具體須要判斷如 heic, heix, mif1 等這些信息。後來在這裏找到。file-extension.net/seeker/網絡

WEBP
Hex Signature
52
複製代碼

判斷 Webp 爲何是截取 0-12 的長度?轉換成 ASCII 以後判斷的依據?優化

在 Google 官方介紹中找到了此圖。說明的是:頭文件的大小是 12Bytesgoogle

WEBP的 header 中寫明瞭 ASCIIRIFF 或者 WEBP Google Developer: developers.google.com/speed/webp/…

明白了原理以後,就是代碼咯!spa

enum ImageFormat {
    case Unknow
    case JPEG
    case PNG
    case GIF
    case TIFF
    case WebP
    case HEIC
    case HEIF
}
extension Data {
    func getImageFormat() -> ImageFormat  {
        var buffer = [UInt8](repeating: 0, count: 1)
        self.copyBytes(to: &buffer, count: 1)
        
        switch buffer {
        case [0xFF]: return .JPEG
        case [0x89]: return .PNG
        case [0x47]: return .GIF
        case [0x49],[0x4D]: return .TIFF
        case [0x52] where self.count >= 12:
            if let str = String(data: self[0...11], encoding: .ascii), str.hasPrefix("RIFF"), str.hasSuffix("WEBP") {
                return .WebP
            }
        case [0x00] where self.count >= 12:
            if let str = String(data: self[8...11], encoding: .ascii) {
                let HEICBitMaps = Set(["heic", "heis", "heix", "hevc", "hevx"])
                if HEICBitMaps.contains(str) {
                    return .HEIC
                }
                let HEIFBitMaps = Set(["mif1", "msf1"])
                if HEIFBitMaps.contains(str) {
                    return .HEIF
                }
            }
        default: break;
        }
        return .Unknow
    }
}
複製代碼
相關文章
相關標籤/搜索