I'm making a program that creates a bitmap file in C. it's using 24-bit colour.
I'm writing the file in 3 stages, i first write the FileHeader, then the InfoHeader, and then the Pixel Data. I'm having trouble padding the pixel data so each row finishes on a word boundary.
The code below works sometimes, but only without the while loop (which adds the padding to the end of the line). For example, with a 12x12px image, I can scale it to 24x24, but not to 10x10 (the file is corrupt). When I put in the padding code below, the image becomes distorted, and sometimes gets corrupted too.
I can't seem to figure out what's going wrong, the code below should add padding to the end of each line until i hits a word boundary, and then starts the next line.
fwrite(&fh, 1, sizeof(FILEHEADER), n_img);
fwrite(&ih, 1, sizeof(INFOHEADER), n_img);
int i, j;
uint8_t pad = 0;
for (i = height-1; i >= 0; i--) {
for (j = 0; j < width; j++)
fwrite(n_pix+(i*width)+j, 1, sizeof(IMAGE), n_img);
while(ftell(n_img)%4 != 0)
fwrite(&pad, 1, 1, n_img);
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…