c - BMP 16位图像转换为数组

标签 c image bmp lcd

我有一个 BMP 格式图像,按以下方式存档

  for (j = 0; j < 240; j++) {
    for(i=0;i<320;i++) { 
      data_temp = LCD_ReadRAM();
      image_buf[i*2+1] = (data_temp&0xff00) >> 8;
      image_buf[i*2+0] = data_temp & 0x00ff;

    }
    ret = f_write(&file, image_buf, 640, &bw);

其中 LCD_ReadRam 函数从 LCD 屏幕一次读取一个像素

我想知道,如何获取该图像文件的像素位置。 以及如何将每个像素的值保存在[320][240]矩阵中
任何帮助将不胜感激,谢谢。

最佳答案

BMP 文件阅读器可以满足您的需求。您可以获得任何好的 BMP 文件阅读器并根据您的目的进行调整。例如:this question and answer给出了假定 24 位 BMP 格式的 BMP 文件读取器。您的格式是 16 位,因此需要进行一些调整。

这是我这样做的尝试(没有测试,所以你应该对硬编码的细节持保留态度)。

int i;
FILE* f = fopen(filename, "rb");
unsigned char info[54];
fread(info, sizeof(unsigned char), 54, f); // read the 54-byte header

int width = 320, height = 240; // might want to extract that info from BMP header instead

int size_in_file = 2 * width * height;
unsigned char* data_from_file = new unsigned char[size_in_file];
fread(data_from_file, sizeof(unsigned char), size_in_file, f); // read the rest
fclose(f);

unsigned char pixels[240 * 320][3];

for(i = 0; i < width * height; ++i)
{
    unsigned char temp0 = data_from_file[i * 2 + 0];
    unsigned char temp1 = data_from_file[i * 2 + 1];
    unsigned pixel_data = temp1 << 8 | temp0;

    // Extract red, green and blue components from the 16 bits
    pixels[i][0] = pixel_data >> 11;
    pixels[i][1] = (pixel_data >> 5) & 0x3f;
    pixels[i][2] = pixel_data & 0x1f;
}

注意:这假设您的 LCD_ReadRAM 函数(大概是从 LCD 内存中读取内容)给出标准 5-6-5 格式的像素。

名称 5-6-5 表示为每个颜色分量(红、绿、蓝)分配的每个 16 位数字中的位数。还存在其他分配,例如 5-5-5 ,但我从未在实践中见过它们。

关于c - BMP 16位图像转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17858581/

相关文章:

c - 所有用户和组的列表

c - 理解 pthread 上的困难

java - 导出 JAR 源图像

c++ - 如何使用 CImage 正确加载灰度 BMP 的字符数组?

c - bmp 图像到 c 中的矩阵(二维数组)

c - 编译c程序时代码段、数据段或创建时间?

javascript - JavaScript 中类型化数组的优点是它们在 C 中的工作方式相同还是相似?

html - 影响其中 child 的CSS背景图像不透明度

java - 图像未加载到 JPanel 中

file - 如何将32位BMP转换为包含Alpha channel ?