# C。读取 BMP 图像像素的问题

##### 问题描述投票：0回答：1

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//Macros
#define ALIGNMENT 4
#define DATA_START_LOCATION 0x000A
#define WIDTH_LOCATION 0x0012
#define HEIGHT_LOCATION 0x0016
#define BITS_PER_PIXEL_LOCATION 0x001C

typedef unsigned char byte;

unsigned int* image_start, const char* file_name)
{
// Here we open the given file for reading in binary mode.
FILE* image = fopen(file_name, "rb");

// Here we check whether opening the given file was successful.
if (image == NULL)
{
printf("Invalid File\n");
return -1;
}

// Here we read in the header of the given BM image.
// Here we read in the height of the given BM image.
fseek(image, HEIGHT_LOCATION, SEEK_SET);
// Here we read in the width of the given BM image.
fseek(image, WIDTH_LOCATION, SEEK_SET);
fseek(image, DATA_START_LOCATION, SEEK_SET);
fclose(image);

return 0;

}

void mapBMP(unsigned int height, unsigned int width, char mapped_image[height][width], unsigned int image_start, const char* file_name)
{
FILE* image = fopen(file_name, "rb");
// Here we read in the number of bits per pixel in the given BM image.
unsigned int bits_per_pixel;
fseek(image, BITS_PER_PIXEL_LOCATION, SEEK_SET);
// Here we compute the number of bytes per pixel in the given BM image.
unsigned int bytes_per_pixel = ((unsigned int) bits_per_pixel) / 8;

// Here we compute the stride, i.e. the number of bytes in a row (rounded up by alignment)
unsigned int stride = (width * bytes_per_pixel) + (ALIGNMENT - 1);
stride /= ALIGNMENT;
stride *= ALIGNMENT;
// Here we read in the pixels of the image, the loops have been shortened for testing purposes.
byte pixel[bytes_per_pixel];
for (unsigned int i = height - 1; i > height - 2; i = i - 1) // The proper condition is:(unsigned int i = height - 1; i > 0; i = i - 1)
{
fseek(image, i * stride, image_start);

for (unsigned int j = 0; j < 30; j = j + 1) // The proper condition is: (unsigned int j = 0; j < width; j = j + 1)
{
printf("pixel = %x %x %x\n", pixel[0], pixel[1], pixel[2]);
}
}

fclose(image);
}

int main()
{

// Here is the BMP Image test.
unsigned int image_width;
unsigned int image_height;
unsigned int image_start;
char* file_name = "dali.bmp";

if (file_opened == -1)
printf("File could not be opened.");
else
{
// Some prints to see the collected data.
printf("Size of byte in byte = %llu \n", sizeof(byte));
printf("height (in pixels) = %u \n", image_height);
printf("width (in pixels) = %u \n", image_width);
printf("image_start (in bytes) = %u \n", image_start);

char mapped_image[image_height][image_width];
mapBMP(image_height, image_width, mapped_image, image_start, file_name);
//printTable(image_height, image_width, mapped_image);
}

return 0;
}
c image pixel
##### 1个回答
0

OP 的代码无法正确读取发布的文件。

uint8_t, uint16_t, uint32_t

char, unsigned

Ref BMP 文件格式