Advertisement
Guest User

Untitled

a guest
Sep 21st, 2017
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.17 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. unsigned char *readBMP(char *filename, int *size) {
  5.     int width, height;
  6.     unsigned char *data;
  7.     unsigned char info[54];
  8.  
  9.     FILE *file = fopen(filename, "rb");
  10.     if (file == NULL)
  11.         return 0;
  12.  
  13.     fread(info, sizeof(unsigned char), 54, file); // read the 54-byte header
  14.  
  15.     // extract image height and width from header
  16.     width = *(int *) &info[18];
  17.     height = *(int *) &info[22];
  18.  
  19.     *size = 3 * width * height;
  20.     data = (unsigned char *) malloc(*size * sizeof(unsigned char)); // allocate 3 bytes per pixel
  21.     fread(data, sizeof(unsigned char), (size_t) *size, file); // read the rest of the data at once
  22.  
  23.     for (int i = 0; i < *size; i += 3) {
  24.         unsigned char tmp = data[i];
  25.         data[i] = data[i + 2];
  26.         data[i + 2] = tmp;
  27.     }
  28.  
  29.     fclose(file);
  30.     return data;
  31. }
  32.  
  33. int main() {
  34.     int size = 0;
  35.     char filename[] = "output.bmp";
  36.     unsigned char *data = readBMP(filename, &size);
  37.  
  38.     for (int i = 0; i < size; i++) {
  39.         printf("%d. %d\n", i + 1, (int) data[i]);
  40.         if ((i + 1) % 3 == 0)
  41.             printf("\n");
  42.     }
  43.  
  44.     free(data);
  45.     return 0;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement