1 /* bmp.c -- bmp write/read api
3 * author: hackbard@hackdaworld.dyndns.org
9 int bmp_init(t_bmp *bmp,int outfd) {
11 dprintf(outfd,"[bmp] initializing bmp api ...\n");
13 memset(bmp,0,sizeof(t_bmp));
19 int bmp_shutdown(t_bmp *bmp) {
22 dprintf(bmp->outfd,"[bmp] free pixmap memory\n");
26 dprintf(bmp->outfd,"[bmp] shutdown\n");
31 int bmp_check_header_and_info(t_bmp *bmp) {
33 if(bmp->info.compression!=0) {
34 dprintf(bmp->outfd,"[bmp] compression not supported\n");
38 if(bmp->info.bpp!=24) {
39 dprintf(bmp->outfd,"[bmp] only true color (24bpp) supported\n");
43 if(bmp->hdr.offset!=B_H_SIZE+B_I_SIZE) {
44 dprintf(bmp->outfd,"[bmp] files with %d bytes offset not supported\n",
49 if(bmp->info.size!=BMP_I_SIZE) {
50 dprintf(bmp->outfd,"[bmp] files with %d bytes info size not supported\n",
58 int bmp_write_file(t_bmp *bmp) {
62 if(!(bmp->mode&WRITE)) {
63 dprintf(bmp->outfd,"[bmp] write mode not specified\n");
69 size=(xsize+fill)*bmp->height;
72 bmp->hdr.identifier='B'|('M'<<8);
73 bmp->hdr.size=size+BMP_H_SIZE+BMP_I_SIZE;
74 bmp->hdr.offset=BMP_H_SIZE+BMP_I_SIZE;
75 bmp->info.size=BMP_I_SIZE;
76 bmp->info.width=bmp->width;
77 bmp->info.height=bmp->height;
80 bmp->info.imagesize=size;
81 if(bmp->info.xres==0) bmp->info.xres=2048;
82 if(bmp->info.yres==0) bmp->info.yres=2048;
87 if((bmp->fd=open(bmp->file,O_WRONLY)<0) {
88 dprintf(bmp->outfd,"[bmp] unable to open file %s\n",bmp->file);
92 if(write(bmp->fd,&(bmp->hdr),BMP_H_SIZE)<BMP_H_SIZE) {
93 dprintf(bmp->outfd,"[bmp] unable to write bmp header\n");
94 return B_E_WRITE_DATA;
97 if(write(bmp->fd,&(bmp->info),BMP_I_SIZE)<BMP_I_SIZE) {
98 dprintf(bmp->outfd,"[bmp] unable to write bmp info\n");
99 return B_E_WRITE_DATA;
106 int bmp_read_file(t_bmp *bmp) {
108 unsigned char buf[BMP_HI_SIZE];
113 if(!(bmp->mode&READ)) {
114 dprintf(bmp->outfd,"[bmp] read mode not specified");
118 if((bmp->fd=open(bmp->file,O_RDONLY))<0) {
119 dprintf(bmp->outfd,"[bmp] unable to open file %s\n",bmp->file);
123 if(read(bmp->fd,buf,BMP_H_SIZE+BMP_I_SIZE)<BMP_H_SIZE+BMP_I_SIZE) {
124 dprintf(bmp->outfd,"[bmp] error reading bmp header & info\n");
128 memcpy(&(bmp->hdr),buf,BMP_H_SIZE);
129 memcpy(&(bmp->info),buf+BMP_H_SIZE,BMP_I_SIZE);
131 if(bmp_check_header_and_info(bmp)!=B_SUCCESS) {
132 dprintf(bmp->outfd,"[bmp] header/info check failed\n");
136 bmp->map=(t_pixel *)malloc(bmp->info.width*bmp->info.height*sizeof(t_pixel));
138 dprintf(bmp->outfd,"[bmp] malloc of map memory failed\n");
142 crop=(bmp->info.imagesize/bmp->info.height)%4;
143 xsize=(bmp->info.bpp/8)*bmp->info.width;
145 for(y=0;y<bmp->info.height;y++) {
146 if(read(bmp->fd,bmp->map+y*bmp->info.width,xsize)<xsize) {
147 dprintf(bmp->outfd,"[bmp] reading image data of line %d failed\n",y);
148 return B_E_READ_DATA;
150 if(read(bmp->fd,buf,crop)<crop) {
151 dprintf(bmp->outfd,"[bmp] failed reading rest of line\n");
152 return B_E_READ_DATA;