Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <errno.h>
- #define HEADER_SIZE 54
- #define PIXEL_SIZE 3
- #define MAX_PATH_SIZE 4096
- int main(int argc, char *argv[]) {
- printf("Starting ...\n");
- int c = 0;
- char input[MAX_PATH_SIZE];
- char output[MAX_PATH_SIZE];
- char * ptr;
- char type[3];
- int keep_going = 1;
- unsigned short int bpp;
- char median = 0;
- char header_tab[HEADER_SIZE];
- char pixel_tab[PIXEL_SIZE];
- char pixel_write_tab[PIXEL_SIZE];
- FILE * fin;
- FILE * fout;
- FILE * temp;
- printf("Enter the file name of a bitmap image :\n");
- if(fgets(input, MAX_PATH_SIZE, stdin) == NULL){
- printf("Error - Unable to get the char\n");
- return 1;
- }
- if((ptr = strchr(input, '\n')) != NULL) *ptr = '\0';
- printf("Enter a file name for output file:\n");
- if(fgets(output, MAX_PATH_SIZE, stdin) == NULL){
- printf("Error - Unable to get the char\n");
- return 1;
- }
- if((ptr = strchr(output, '\n')) != NULL) *ptr = '\0';
- if (!(temp = fopen(input, "rb"))) {
- printf("Error - Unable to open the file given (errno:%d)\n", errno);
- return 1;
- }
- fseek(temp,0,0);
- fread(type,1,2,temp);
- type[2] = '\0';
- fseek(temp,28,0);
- fread(&bpp,1,2,temp);
- if (strcmp(type,"BM") || (bpp != 24)){
- printf("Error - The file is not BMP format or is not 24 bits\n");
- exit(0);
- }
- if(strcmp(input, output) != 0){
- fin = fopen(input, "rb");
- //Read header
- c = fread(header_tab, 1, HEADER_SIZE ,fin);
- if (c<HEADER_SIZE){
- printf("Warning - Header to small\n Exiting properly ...\n");
- fclose(fin);
- exit(1);
- }
- if (!(fout = fopen(output, "wb"))) {
- printf("Error - Unable to open the output file (errno:%d)\n", errno);
- fclose(fin);
- return 1;
- }
- //Write header
- fwrite(header_tab, 1, HEADER_SIZE, fout);
- //To shade of grey
- do
- {
- c = fread(pixel_tab, 1,PIXEL_SIZE, fin);
- if (c!=3){
- keep_going = 0;
- } else {
- median = (char) ((pixel_tab[0] + pixel_tab[1] + pixel_tab[2]) / 3);
- pixel_write_tab[0] = median;
- pixel_write_tab[1] = median;
- pixel_write_tab[2] = median;
- fwrite(pixel_write_tab, 1, PIXEL_SIZE, fout);
- }
- }
- while (keep_going == 1);
- }
- else{
- printf("Error - Unable to write the output in the same file");
- fclose(fin);
- return 1;
- }
- fclose(fin);
- fclose(fout);
- printf("Ending without errors\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement