前面提高了一个将BMP左转的程序,右转其实也是类似的操作,就不写了,这节,我们来实现,将一张BMP图进行灰度处理,代码贴上:
#include <stdio.h> #include <fcntl.h> #include <unistd.h> #define RGB(r,g,b) ((r+g+b)/3) typedef unsigned char U8 ; typedef unsigned short U16 ; typedef unsigned int U32 ; #pragma pack(1) struct bmp_header { //bmp header U8 Signatue[2] ; // B M U32 FileSize ; //文件大小 U16 Reserv1 ; U16 Reserv2 ; U32 FileOffset ; //文件头偏移量 //DIB header U32 DIBHeaderSize ; //DIB头大小 U32 ImageWidth ; //文件宽度 U32 ImageHight ; //文件高度 U16 Planes ; U16 BPP ; //每个相素点的位数 U32 Compression ; U32 ImageSize ; //图文件大小 U32 XPPM ; U32 YPPM ; U32 CCT ; U32 ICC ; }; #pragma pack() int main(int argc , char **argv) { if(argc != 4) return -1 ; int fd ; int dest_fd ; fd = open(argv[1] , O_RDONLY); if(-1 == fd) { perror("open bmp file fail"); return -2 ; } dest_fd = open( argv[2] , O_RDWR | O_CREAT|O_TRUNC , 0777); if(dest_fd < 0 ) { perror("open rgb565 fail"); return -3 ; } int value = atoi(argv[3]); struct bmp_header header ; int ret ; ret = read(fd , &header , sizeof(struct bmp_header)); printf(" Signatue[0] : %c \n " , header.Signatue[0] ); printf(" Signatue[1] : %c \n " , header.Signatue[1] ); printf(" FileSize : %d \n " , header.FileSize ); printf(" Reserv1 : %d \n " , header.Reserv1 ); printf(" Reserv2 : %d \n " , header.Reserv2 ); printf(" FileOffset : %d \n " , header.FileOffset ); printf(" DIBHeaderSize : %d \n " , header.DIBHeaderSize); printf(" ImageWidth : %d \n " , header.ImageWidth ); printf(" ImageHight : %d \n " , header.ImageHight ); printf(" Planes : %d \n " , header.Planes ); printf(" BPP : %d \n " , header.BPP ); printf(" Compression : %d \n " , header.Compression ); printf(" ImageSize : %d \n " , header.ImageSize ); printf(" XPPM : %d \n " , header.XPPM ); printf(" YPPM : %d \n " , header.YPPM ); printf(" CCT : %d \n " , header.CCT ); printf(" ICC : %d \n " , header.ICC ); char buffer[header.ImageSize] ; read(fd , buffer , header.ImageSize); close(fd); //改变地方 write(dest_fd , &header , sizeof(struct bmp_header)); int row , col ; char *p = NULL ; for(row = 0 ; row < 10 ; row++) { for(col = 0 ; col < 10 ; col++) { p = buffer + (row * 800 + col)*3 ; *p = 255; *(p+1)=255; *(p+2)=255; } } char data ; for(row = 0 ; row < 480 ; row++) { for(col = 0 ; col < 800 ; col++) { p =( buffer+(row*800 + col)*3); data = RGB((unsigned char)(*(p+2)) , (unsigned char)(*(p+1)) , (unsigned char )(*(p))); if(data < value) { *p = 0; *(p+1)=0; *(p+2)=0; } else { *p = data; *(p+1)=data; *(p+2)=data; } write(dest_fd , p , 3); } } close(dest_fd); return 0 ; }
时间: 2024-10-26 05:48:07