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)
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);
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With