无法读取PNG文件的IHDR块

时间:2019-02-23 20:12:02

标签: swift png nsfilehandle

我已经阅读了PNG文件规范,并了解到在PNG签名的前8个字节之后,我们有了IHDR块。此图表明我们的IHDR的长度为13(0x0000000D)个字节。 enter image description here

我迅速编写了一个代码,以读取相同的png文件并打印字节,该字节不会给我一个IHDR,其长度等于PNG签名后的块的前4个字节中的13个字节。控制台中代码的输出为

PNG Signature Bytes: 89 50 4E 47 0D 0A 1A 0A 
File offset: 8
IHDR length bytes: 00 00 00 04 
File offset: 12
IHDR Chunktype bytes: 43 67 42 49 
File offset: 16
IHDR Data byte: 50 00 20 02 
File offset: 20
pngImageWidth: 1342185474
pngImageWidth: 20480
pngImageHeight: 8194

我在这里错过了一些东西吗,或者我阅读的规范已经过时了?

前8个字节是实际的PNG签名字节。 IHDR字节是我无法获得预期的长度和块类型的地方(IHDR的宽度,高度和其他字节对于不同的文件是可变的,但是长度和块类型应与我的阅读相同)。

直接读取png文件的代码如下:

enum PNGFileAnatomyConstants {
    static let pngSignatureLength = 8
    static let ihdrLength = 4
    static let chunkTypeLength = 4
    static let chunkCRCLength = 4
    static let imageWidthLength = 4
    static let imageHeigthLength = 4
}

func anatomyOfPNGFile() {
    let bundle = Bundle.main

    guard let pngFileUrl = bundle.url(forResource: "PNGFileSignature", withExtension: "png") else { fatalError() }

    do {
        // Signature start------------------------------------------------------------------------------------------

        let readFileHandle = try FileHandle(forReadingFrom: pngFileUrl)
        defer {
            readFileHandle.closeFile()
        }
        let pngSignatureData = readFileHandle.readData(ofLength: PNGFileAnatomyConstants.pngSignatureLength)
        let signatureString  = pngSignatureData.hexEncodedString(options: [Data.HexEncodingOptions.upperCase])
        if signatureString != "89 50 4E 47 0D 0A 1A 0A " {
            fatalError(" Not a png")
        }
        print("PNG Signature Bytes: \(signatureString)")
        print("File offset: \(readFileHandle.offsetInFile)")
        // Signature ebd------------------------------------------------------------------------------------------




        // IHDR Length start------------------------------------------------------------------------------------------
        let ihdrLengthDataBigEndian = readFileHandle.readData(ofLength: PNGFileAnatomyConstants.ihdrLength)

        let ihdrLength: UInt32
        if PlatformEndianess.isLittleEndian {
            ihdrLength = Data(ihdrLengthDataBigEndian.reversed()).withUnsafeBytes({ (unsafePointer: UnsafePointer<UInt32>) -> UInt32 in
                return unsafePointer.pointee
            })
        } else {
            ihdrLength = ihdrLengthDataBigEndian.withUnsafeBytes({ (unsafePointer: UnsafePointer<UInt32>) -> UInt32 in
                return unsafePointer.pointee
            })
        }

        let ihdrLengthDataBigEndianString = ihdrLengthDataBigEndian.hexEncodedString(options: [.upperCase])
        print("IHDR length bytes: \(ihdrLengthDataBigEndianString)")
        print("File offset: \(readFileHandle.offsetInFile)")
        // IHDR Length end------------------------------------------------------------------------------------------





        // IHDR chunk type start------------------------------------------------------------------------------------------
        let ihdrChunkTypeData = readFileHandle.readData(ofLength: PNGFileAnatomyConstants.chunkTypeLength)
        let ihdrChunkTypeDataString  = ihdrChunkTypeData.hexEncodedString(options: [Data.HexEncodingOptions.upperCase])
        print("IHDR Chunktype bytes: \(ihdrChunkTypeDataString)")
        print("File offset: \(readFileHandle.offsetInFile)")
        // IHDR chunk type end------------------------------------------------------------------------------------------



        // IHDR data byte start------------------------------------------------------------------------------------------
        let ihdrData = readFileHandle.readData(ofLength: Int(ihdrLength))
        let ihdrDataString = ihdrData.hexEncodedString(options: [.upperCase])
        print("IHDR Data byte: \(ihdrDataString)")
        print("File offset: \(readFileHandle.offsetInFile)")
        // IHDR data byte end------------------------------------------------------------------------------------------

        do {
            let pngImageWidth: UInt32
            if PlatformEndianess.isLittleEndian {
                pngImageWidth = Data(ihdrData.reversed()).withUnsafeBytes({ (unsafePointer: UnsafePointer<UInt32>) -> UInt32 in
                    return unsafePointer.pointee
                })
            } else {
                pngImageWidth = ihdrData.withUnsafeBytes({ (unsafePointer: UnsafePointer<UInt32>) -> UInt32 in
                    return unsafePointer.pointee
                })
            }

            print("pngImageWidth: \(pngImageWidth)")
        }

        do {
            let pngImageWidth: UInt16
            let widthData = Data(bytes: [ihdrData[0], ihdrData[1]])
            if PlatformEndianess.isLittleEndian {

                pngImageWidth = Data(widthData.reversed()).withUnsafeBytes({ (unsafePointer: UnsafePointer<UInt16>) -> UInt16 in
                    return unsafePointer.pointee
                })
            } else {
                pngImageWidth = widthData.withUnsafeBytes({ (unsafePointer: UnsafePointer<UInt16>) -> UInt16 in
                    return unsafePointer.pointee
                })
            }

            print("pngImageWidth: \(pngImageWidth)")//20480

            let pngImageHeight: UInt16
            let heightData = Data(bytes: [ihdrData[2], ihdrData[3]])
            if PlatformEndianess.isLittleEndian {

                pngImageHeight = Data(heightData.reversed()).withUnsafeBytes({ (unsafePointer: UnsafePointer<UInt16>) -> UInt16 in
                    return unsafePointer.pointee
                })
            } else {
                pngImageHeight = heightData.withUnsafeBytes({ (unsafePointer: UnsafePointer<UInt16>) -> UInt16 in
                    return unsafePointer.pointee
                })
            }

            print("pngImageHeight: \(pngImageHeight)")//20480
        }

    } catch {
        fatalError(error.localizedDescription)
    }
}

extension Data {
    struct HexEncodingOptions: OptionSet {
        let rawValue: Int
        static let upperCase = HexEncodingOptions(rawValue: 1 << 0)
    }

    func hexEncodedString(options: HexEncodingOptions = []) -> String {
        let hexDigits = Array((options.contains(.upperCase) ? "0123456789ABCDEF " : "0123456789abcdef ").utf16)
        var chars: [unichar] = []
        chars.reserveCapacity(3 * count)
        for byte in self {
            chars.append(hexDigits[Int(byte / 16)])
            chars.append(hexDigits[Int(byte % 16)])
            chars.append(hexDigits.last!)
        }
        return String(utf16CodeUnits: chars, count: chars.count)
    }
}

class PlatformEndianess {
    static var isLittleEndian: Bool = {
        var integer: UInt16 = 0x0001
        return withUnsafeBytes(of: &integer, { (rawBufferPointer) -> Bool in
            return rawBufferPointer.first == 0x01
        })
    }()
}

1 个答案:

答案 0 :(得分:0)

MartinR所指出的那样,PNG文件上有一个扩展名,称为CgBI

普通PNG文件的结构是PNG签名后跟IHDR块。

以下是普通PNG文件的十六进制表示形式的字节示例(xx是具有可变值的占位符字节):

PNG Signature(8 bytes): 89 50 4E 47 0D 0A 1A 0A
=======Chunk start=======
IHDR Chunk:
    IHDR chunk length(4 bytes): 00 00 00 0D
    IHDR chunk type(Identifies chunk type to be IHDR): 49 48 44 52
    Image width in pixels(variable 4): xx xx xx xx
    Image height in pixels(variable 4): xx xx xx xx
    Flags in the chunk(variable 5 bytes): xx xx xx xx xx
    CRC checksum(variable 4 bytes): xx xx xx xx 
=======Chunk end=======

具有CgBI扩展名的PNG文件具有以下结构:PNG签名后跟CgBI块,然后是IHDR块。

当我说扩展名时,请不要将其混淆为“ filename.png,filename.cgbi”。它实际上是应该构造PNG文件的方式的扩展。

以下是具有CgBI扩展名的PNG文件的十六进制表示形式的字节示例(xx是具有可变值的占位符字节):

PNG Signature(8 bytes): 89 50 4E 47 0D 0A 1A 0A
=======Chunk start=======
CgBI Chunk:
    CgBI chunk length(4 bytes): 00 00 00 04
    CgBI chunk type(Identifies chunk type to be CgBI): 43 67 42 49
    CgBI info flags(4 bytes): xx xx xx xx
    CRC checksum(variable 4 bytes): xx xx xx xx 
=======Chunk end=======
=======Chunk start=======
IHDR Chunk:
    IHDR chunk length(4 bytes): 00 00 00 0D
    IHDR chunk type(Identifies chunk type to be IHDR): 49 48 44 52
    Image width in pixels(variable 4): xx xx xx xx
    Image height in pixels(variable 4): xx xx xx xx
    Flags in the chunk(variable 5 bytes): xx xx xx xx xx
    CRC checksum(variable 4 bytes): xx xx xx xx 
=======Chunk end=======

虽然PNG文件在所有图像查看器上呈现,但扩展名CgBI可能会或可能不会在所有图像查看器上呈现,这取决于它们为此类文件提供的支持。

MacOS预览版可以显示此类图像,而iOS上的UIImageView也可以显示我的图像示例集中具有扩展名CNG的PNG文件。