Search code examples
c++imagepng

C++ How to get the Image size of a png file (in directory)


Is there a way of getting the dimensions of a png file in a specific path? I don´t need to load the file, I just need the width and height to load a texture in directx.

(And I don´t want to use any third-party-libs)


Solution

  • The width is a 4-byte integer starting at offset 16 in the file. The height is another 4-byte integer starting at offset 20. They're both in network order, so you need to convert to host order to interpret them correctly.

    #include <fstream>
    #include <iostream>
    #include <winsock.h>
    
    int main(int argc, char **argv) { 
        std::ifstream in(argv[1]);
        unsigned int width, height;
    
        in.seekg(16);
        in.read((char *)&width, 4);
        in.read((char *)&height, 4);
    
        width = ntohl(width);
        height = ntohl(height);
    
        std::cout << argv[1] << " is " << width << " pixels wide and " << height << " pixels high.\n";
        return 0;
    }
    

    As-is, this is for windows. For Linux (or *bsd, etc.) you'll need to #include <arpa/inet.h> instead of <winsock.h>.