Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

image

png

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)

like image 393
Alex Kruger Avatar asked Mar 18 '11 15:03

Alex Kruger


2 Answers

Based on @Jerry answer, but without winsock.h included

        void get_png_image_dimensions(std::string& file_path, unsigned int& width, unsigned int& height)
        {
            unsigned char buf[8];
            
            std::ifstream in(file_path);
            in.seekg(16);
            in.read(reinterpret_cast<char*>(&buf), 8);

            width = (buf[0] << 24) + (buf[1] << 16) + (buf[2] << 8) + (buf[3] << 0);
            height = (buf[4] << 24) + (buf[5] << 16) + (buf[6] << 8) + (buf[7] << 0);
        }
like image 102
Aliaksei Luferau Avatar answered Oct 16 '22 17:10

Aliaksei Luferau


No, you can't do it without reading part of the file. Fortunately, the file headers are simple enough that you can read them without a library, if you don't need to read the actual image data.

If you know for sure that you have a valid PNG file, you can read the width and height from offsets 16 and 20 (4 bytes each, big-endian), but it may also be a good idea to verify that the first 8 bytes of the file are exactly "89 50 4E 47 0D 0A 1A 0A" (hex) and that bytes 12-15 are exactly "49 48 44 52" ("IHDR" in ASCII).

like image 28
Adam Rosenfield Avatar answered Oct 16 '22 17:10

Adam Rosenfield