Created
January 17, 2019 09:10
-
-
Save edwardean/3e9d3a84974207570d038bb45d0e13b1 to your computer and use it in GitHub Desktop.
检查图片类型
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let data: Data? = try? Data(contentsOf: Bundle.main.url(forResource: "exposure_tab_gray_arrow_right@2x", withExtension: "png")!) | |
internal struct ImageHeaderData { | |
static var PNG: [UInt8] = [0x89] | |
static var JPEG: [UInt8] = [0xFF] | |
static var GIF: [UInt8] = [0x47] | |
static var BMP: [UInt8] = [0x42] | |
static var TIFF_01: [UInt8] = [0x49] | |
static var TIFF_02: [UInt8] = [0x4D] | |
} | |
do { | |
let start = (data! as NSData).bytes.bindMemory(to: UInt8.self, capacity: data!.count) | |
let byte: UInt8? = UnsafeBufferPointer(start: start, count: 1).first | |
print(byte as Any) | |
switch byte { | |
case ImageHeaderData.PNG: | |
return .PNG | |
case ImageHeaderData.JPEG: | |
return .JPEG | |
case ImageHeaderData.GIF: | |
return .GIF | |
case ImageHeaderData.TIFF_01: | |
fallthrough | |
case ImageHeaderData.TIFF_02: | |
return .TIFF | |
case ImageHeaderData.BMP: | |
return .BMP | |
} | |
} | |
do { | |
var buffer = [UInt8](repeating: 0, count: 1) | |
(data! as NSData).getBytes(&buffer, range: NSRange(location: 0, length: 1)) | |
print(buffer as Any) | |
switch buffer { | |
case ImageHeaderData.PNG: | |
return .PNG | |
case ImageHeaderData.JPEG: | |
return .JPEG | |
case ImageHeaderData.GIF: | |
return .GIF | |
case ImageHeaderData.TIFF_01: | |
fallthrough | |
case ImageHeaderData.TIFF_02: | |
return .TIFF | |
case ImageHeaderData.BMP: | |
return .BMP | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment