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)
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)
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>
.
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).
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.
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);
}
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.
© 2022 - 2024 — McMap. All rights reserved.