将Bmp Greyscales读入C语言

时间:2011-03-18 09:24:10

标签: c++ c postgresql bmp grayscale

我在C下查找了如何将Bmp文件读入2维或1维数组,有许多解决方案但不是我需要的解决方案。 我需要将黑白bmp读入(开始)2维数组,其中必须包含0到255之间的值(灰度) 然后将其转换为1维数组(但这不是问题)。 Matlab自动完成这个,但我想在C / C ++下更自主地工作 最后,bmp应保存到Postgre数据库int数组中。 感谢

2 个答案:

答案 0 :(得分:0)

对不起,误读了问题:/
如果你不介意“扭曲”规则一点点

#include <stdio.h>

int main(void) {
  int data[100][30] = {{0}}; /* initialize 2D array to all zeroes */
  int *p1d;
  size_t index;

  data[42][20] = 42; /* set 1 element ot 42 */
  p1d = &data[0][0];
  index = 42*30 + 20;
  printf("%d (should be 42)\n", p1d[index]); /* pretend it's a 1D array */
  return 0;
}

答案 1 :(得分:0)

我为另一个问题做了一个bmp装载机:
http://nishi.dreamhosters.com/u/so_bmp_v0.zip
示例bmp有RGB,但它似乎也适用于灰度。

FILE* f = fopen( "winnt.bmp", "rb" ); if( f==0 ) return 1;
fread( buf, 1,sizeof(buf), f );
fclose(f);

BITMAPFILEHEADER& bfh = (BITMAPFILEHEADER&)buf[0];
BITMAPINFO& bi = (BITMAPINFO&)buf[sizeof(BITMAPFILEHEADER)];
BITMAPINFOHEADER& bih = bi.bmiHeader; 
char* bitmap = &buf[bfh.bfOffBits];
int SX=bih.biWidth, SY=bih.biHeight;

位图这里是指向像素表的指针(应该是无符号的 为了正确访问)。请注意,bmp中的像素行可以存储在 逆序。