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

5

9

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)

Durrett answered 18/3, 2011 at 15:47 Comment(0)
V
17

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>.

Vernavernacular answered 18/3, 2011 at 16:2 Comment(0)
U
7

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).

Uird answered 18/3, 2011 at 15:55 Comment(0)
T
3

The size of the image is located in the header, so you'll need to load the file and parse the header.

So, since you don't want to use a third party library, you can always check the PNG specs and implement your own parser.

Thionic answered 18/3, 2011 at 15:50 Comment(0)
D
3

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);
        }
Diego answered 8/9, 2021 at 15:11 Comment(0)
P
1

You can always decode the file manually and just look for the bits you're interested in. Here's a link to an article about PNG file formats.. You're looking for the IHDR chunk and that contains the width and height. It should be the first bit of data in the file so it should be quite easy to get at.

Papillote answered 18/3, 2011 at 15:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.