简体   繁体   中英

Text File to Bitmap in C Program

I'm very new in C programming and I am trying make a program that reads a text file and makes a black and white bmp out of it. I think my code is almost done, but I only get a black image.

What am I missing or what'ss wrong?

0000000000

0000110000 

0001111000

0011111100

0111111110

1111111111

0111111110

0011111100

0001111000

0000110000

Here is code:

#include <stdio.h>
#include <strings.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>

 int k = 0;

#pragma pack(1)
    typedef struct{
     uint16_t bfType;
     uint32_t bfSize;
 uint16_t bfReserved1;
 uint16_t bfReserved2;
 uint32_t bfOffBits;
} BMPFH;
#pragma pack()

#pragma pack(1)
typedef struct{
uint32_t biSize;
int32_t biWidth;
int32_t biHeight;
uint16_t  biPlanes;
uint16_t biBitCount;
uint32_t biCompression;
uint32_t bisizeImage;
int32_t biXPelsPerMeter;
int32_t biYPelsPerMeter;
uint32_t biClrUsed;
uint32_t biClrImportant;
} BMIH;
#pragma pack()

#pragma pack(1)
typedef struct {
BMPFH BMPFH;
BMIH BMIH;
} bitmap;
#pragma pack()

int main() {
 FILE * input = fopen("/Users/JosPaduaA/desktop/dibujo1.txt", "r");
        char txt[100];
        int bmp[2400] = {0};
        int j = 0, i = 0;
        fread(txt, 100, 1, input);
        fclose(input);
        while(i < 100){
                if(txt[i] == '1'){
                        for(j = 0; j < 24; j++){
                                bmp[k] = 1;
                                k++;
                        }
                }
                else{
                        k += 24;
                }
        i++;
        }
BMPFH fh;
BMIH ih;
FILE* file = fopen("out.bmp","wb");

memcpy(&fh.bfType,"BM",2);
fh.bfSize = 14+40+320; //ERROR
fh.bfOffBits = 14+40;
fh.bfReserved1 = 0;
fh.bfReserved2 = 0;

ih.biSize = 40;
ih.biWidth = 10;
ih.biHeight = 10;
ih.biPlanes = 1;
ih.biBitCount = 24;
ih.biCompression = 0;
ih.bisizeImage = 0;
ih.biXPelsPerMeter = 0;
ih.biYPelsPerMeter = 0;
ih.biClrUsed = 0;
ih.biClrImportant = 0;

fwrite(&fh,sizeof(fh),1,file);
fwrite(&ih,sizeof(ih),1,file);
unsigned int data_size = fh.bfSize - sizeof(bitmap);
uint8_t *pixelbuffer = (uint8_t*)malloc(data_size);
bitmap *pbitmap  = (bitmap*)calloc(1,sizeof(bitmap));
memset(pixelbuffer, 0, data_size);
fwrite(pixelbuffer, 1, data_size, file);
fclose(file);
free(pixelbuffer);
return 0;
}

this line:

memset(pixelbuffer, 0, data_size);

is setting all the pixel values to 0x00 0x00 0x00 , which is black

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM