Iliqn Tachev
Iliqn Tachev

Reputation: 31

Get the height and weight of a png image

I am trying to get the height and weight of a PNG image using pointers to the locations at both in the PNG file.

I read the memory using read_image(), but what I get this way is width: 115200 and height: 115464, but my picture has width: 450; height: 451.

Here is my code:

    #include<stdio.h>
    #include<stdint.h>
    #include<arpa/inet.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <stdlib.h>

    void *read_image( const char *filepath );
    int main(int argc, char** argv)
    {
      char *ptr=read_image(argv[1]);
      uint32_t *point1=ptr+17;
      uint32_t *point2=ptr+21;
      uint32_t point1_res=ntohl(*point1);
      uint32_t point2_res=ntohl(*point2);
      printf("\nWidth: %d",point1_res);
      printf("\nHeight: %d",point2_res);
      return 0;
     }
     void *read_image(char *path) {
      int fd = open(path, O_RDONLY);
      if (fd < 0) {
        return NULL;
      }
      size_t size = 1000;
      size_t offset = 0;
      size_t res;
      char *buff = malloc(size);

      while((res = read(fd, buff + offset, 100)) != 0) {
            offset += res;
            if (offset + 100 > size) {
                    size *= 2;
                    buff = realloc(buff, size);
            }
      }
      close(fd);
      return buff; 
     }

There is no problem with my read_image() function, I am thinking of ntohl()?

Upvotes: 0

Views: 1414

Answers (1)

alk
alk

Reputation: 70911

The PNG's width shall be at offset 16, the height at offset 20.

So change this

  uint32_t *point1=ptr+17;
  uint32_t *point2=ptr+21;

to be

  uint32_t *point1=ptr+16;
  uint32_t *point2=ptr+20;

(Details on the PNG format are here.)

Upvotes: 2

Related Questions