Advertisement
Guest User

Writing bmp in C

a guest
Jan 8th, 2012
13,040
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.35 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <fcntl.h>
  3. #include <unistd.h>
  4. #include <stdio.h>
  5.  
  6. //define pixelformat of windows bitmap, notice the unusual ordering of colors
  7. typedef struct {
  8.     unsigned char B;
  9.     unsigned char G;
  10.     unsigned char R;
  11. } pixel;
  12.  
  13. //supply an array of pixels[height][width] <- notice that height comes first
  14. int writeBMP(char* filename, unsigned int width, unsigned int height, pixel** pixels) {
  15.     int fd = open(filename, O_WRONLY|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);  
  16.     static unsigned char header[54] = {66,77,0,0,0,0,0,0,0,0,54,0,0,0,40,0,0,0,0,0,0,0,0,0,0,0,1,0,24}; //rest is zeroes
  17.     unsigned int pixelBytesPerRow = width*sizeof(pixel);
  18.     unsigned int paddingBytesPerRow = (4-(pixelBytesPerRow%4))%4;
  19.     unsigned int* sizeOfFileEntry = (unsigned int*) &header[2];
  20.     *sizeOfFileEntry = 54 + (pixelBytesPerRow+paddingBytesPerRow)*height;  
  21.     unsigned int* widthEntry = (unsigned int*) &header[18];    
  22.     *widthEntry = width;
  23.     unsigned int* heightEntry = (unsigned int*) &header[22];    
  24.     *heightEntry = height;    
  25.     write(fd, header, 54);
  26.     static unsigned char zeroes[3] = {0,0,0}; //for padding    
  27.     for (int row = 0; row < height; row++) {
  28.         write(fd,pixels[row],pixelBytesPerRow);
  29.         write(fd,zeroes,paddingBytesPerRow);
  30.     }
  31.     close(fd);
  32.     return 0;
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement