Clarence Ng
Clarence Ng

Reputation: 15

c++ visual studio 2017 reading png dimension through header data

Hello i have problem to read out the correct data of png dimesnion size

unsigned  width = 0;
unsigned  height = 0;
bool output_json = false;
std::ifstream in(filepath, std::ios_base::binary | std::ios_base::in);
if (in.is_open())
{
    in.seekg(16, std::ios_base::cur);
    in.read((char *)&width, 4);
    in.read((char *)&height, 4);

    _byteswap_uint64(width);
    _byteswap_uint64(height);

    output_json = true;
    in.close();
}

the width should be 155 , but output 2600468480 the height should be 80, but output 1342177280

Upvotes: 0

Views: 47

Answers (1)

max66
max66

Reputation: 66200

the width should be 155 , but output 2600468480 the height should be 80, but output 1342177280

There is a problem of endianess.

2600468480 is, in exadecimal form 9b000000; 155 is 9b.

So the order of the less significat / most significant bytes is switched.

Try swapping the bytes

unsigned  w0;

in.read((char *)&w0, 4);

width = ((w0 >> 24) & 0xff) |
        ((w0 << 8) & 0xff0000) |
        ((w0 >> 8) & 0xff00) |
        ((w0 << 24) & 0xff000000); 

Upvotes: 1

Related Questions