我正在努力输入BMP,然后操纵我的2D像素阵列中的几乎每个像素,并将其存储在数组2D pixelarrayout中(在下面的最终代码段中的第一个嵌套for循环内部)。我觉得输出的BMP应该是正常的,当通过Hex编辑器查看文件时,一切似乎都没问题,但由于某种原因,文件无法正常打开。有什么想法吗?可能是标题中的错误,但每个文件的前54个字节(两个标题的大小)是相同的
//make an instance of all output structure
HEADER dataoutput;
INFOHEADER data2output;
char pixeloutput[pixelnum];
int pixcount=0;
for(r=0; r<rows; r++){
for(c=0; c<collumns;c++){
pixeloutput[pixcount]=pixelarrayout[r][c].Red;
pixcount++;
}
}
dataoutput.Type = data.Type;
dataoutput.Size = data.Size;
dataoutput.Reserved1 = data.Reserved1;
dataoutput.Reserved2 = data.Reserved2;
dataoutput.Offset = data.Offset;
data2output.Size = data2.Size;
data2output.Width = data2.Width;
data2output.Height = data2.Height;
data2output.Planes = data2.Planes;
data2output.Bits = data2.Bits;
data2output.Compression = data2.Compression;
data2output.ImageSize = data2.ImageSize;
data2output.xResolution = data2.xResolution;
data2output.yResolution = data2.yResolution;
data2output.Colors = 0;
data2output.ImportantColors = 0;
if( !(fileout = fopen( "CUoutput4.bmp","wb")))return 0;
//calloc an array of 16 bytes set to NULL to be used to pad the end of the file
char *nullarray;
nullarray = (char*) calloc(16,sizeof(char));
fwrite(&dataoutput,sizeof(HEADER),1,fileout);
fwrite(&data2output,sizeof(INFOHEADER),1,fileout);
int i;
char *pixelvaluehold;
for(i=0;i<pixelnum;i++){
pixelvaluehold = &pixeloutput[i];
fwrite(pixelvaluehold,sizeof(char),1,fileout);
}
int count=0;
while(( count + sizeof(HEADER) + sizeof(INFOHEADER) + pixelnum * sizeof(PIXEL) ) % 16 != 0){
fwrite(nullarray,sizeof(char),1,fileout);
count++;
}
fclose(file);
fclose(fileout);
free(pixelarray);
free(pixelarrayout);
以下是HEADER,INFOHEADER和PIXEL的结构
//define structures
typedef struct
{ unsigned short int Type; /* Magic identifier */
unsigned int Size; /* File size in bytes */
unsigned short int Reserved1, Reserved2;
unsigned int Offset; /* Offset to data (in B)*/
}HEADER; /* -- 14 Bytes -- */
typedef struct
{ unsigned int Size; /* Header size in bytes */
unsigned int Width, Height; /* Width / Height of image */
unsigned short int Planes; /* Number of colour planes */
unsigned short int Bits; /* Bits per pixel */
unsigned int Compression; /* Compression type */
unsigned int ImageSize; /* Image size in bytes */
int xResolution, yResolution;/* Pixels per meter */
unsigned int Colors; /* Number of colors */
unsigned int ImportantColors;/* Important colors */
}INFOHEADER; /* -- 40 Bytes -- */
//restor original stack allignment
#pragma pack(pop)
typedef struct
{ unsigned char Red, Blue, Green;
}PIXEL;