c - 获取png图像的高度和重量

标签 c pointers memory png

我正在尝试使用指向 PNG 文件中两个位置的指针来获取 PNG 图像的高度和重量。

我使用read_image()读取内存,但是我这样得到的是width: 115200和height: 115464,但是我的图片有width: 450;高度:451。

这是我的代码:

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

我的read_image()函数没有问题,我在想ntohl()

最佳答案

PNG 的宽度应位于偏移量 16 处,高度应位于偏移量 20 处。

所以改变这个

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

成为

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

( Details on the PNG format are here. )

关于c - 获取png图像的高度和重量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46619303/

相关文章:

c# - 改变数组的一个元素会改变其他元素

c - 操作系统内存管理,段错误?

编译器/语言运行时与中间件

c++ - 指向类的双指针

c++ - 如何删除二维数组?

c++ - C++ 中枚举数的作用域

c - 需要帮助破译 C 语法

c - 如何将 512KB 数据的 SHA1 与元信息文件中给定的 SHA1 进行比较?

c - 比变量小的指针类型

java - 多维数组声明中的顺序对已用内存有影响吗?