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

元气小坏坏 提交于 2019-12-18 03:43:49

问题


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)


回答1:


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;
}



回答2:


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




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




回答4:


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.



来源:https://stackoverflow.com/questions/5354459/c-how-to-get-the-image-size-of-a-png-file-in-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!