在c中提取BMP图像的宽度

时间:2018-06-18 11:33:04

标签: c image-processing bmp

我是一名初学程序员并尝试在c中学习图像处理并找到一些教程,但我被困在一条线(它负责提取 width int width = *(int*)&header[18]; 我无法理解上面的语法。 任何人都可以简单解释一下吗?

1 个答案:

答案 0 :(得分:2)

int width = *(int*)&header[18];

Assuming header is of type char* or char[], piece for piece:

header[18]

→ get element 18 of header

&header[18]

→ get address of element 18 of header

(int*)&header[18]

→ cast address of element 18 of header to pointer to int

*(int*)&header[18]

→ get contents of that pointer to int.


The values in a BMP file are stored little-endian. Hence, this code will work on a little-endian platform only. A more general code would look like this:

int width
  = (unsigned)(unsigned char)header[18]
  | (unsigned)(unsigned char)header[19] << 8
  | (unsigned)(unsigned char)header[20] << 16
  | (unsigned)(unsigned char)header[21] << 24;

The int width is now composed out of individual bytes shifted to their according position. This should work on every endianess.