代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>
int main(int argc, const char *argv[])
{int size_bmp=0;int length_bmp=0;int hight_bmp=0;FILE* fp=fopen(argv[1],"r");fseek(fp,2,SEEK_SET);//偏移2,找到文件写入大小的位置;fread(&size_bmp,1,4,fp);fseek(fp,18,SEEK_SET);//找到文件写入图片宽度位置fread(&length_bmp,1,4,fp);//fseek(fp,22,SEEK_SET);fread(&hight_bmp,1,4,fp);//此时光标已经到23的位置,从该位置读取图片的高printf("%d\n%d\n%d\n",size_bmp,length_bmp,hight_bmp);fclose(fp);//像素点总数为length_bmp*hight_bmp=1330155//从54位后(不含54)是存放像素点的信息,所以像素点存放的总字节大小为size_bmp-54=3993120//则每个像素点的字节大小为像素总字节/像素点总数=3993120/1330155=3unsigned char red[3]={0,0,255};unsigned char yellow[3]={0,255,255};unsigned char black[3]={0,0,0};fp=fopen(argv[1],"r+");//防止第二次打开时把图片文件内容清空fseek(fp,54,SEEK_SET);//使光标指向像素点开始的位置int i;for(i=0;i<hight_bmp;i++){for(int j=0;j<length_bmp;j++){if(i<=(hight_bmp/3)){fwrite(yellow,3,1,fp);}else if(i>(hight_bmp/3) && i<=(hight_bmp*2/3)){fwrite(red,3,1,fp);}else{fwrite(black,3,1,fp);}}}fclose(fp);return 0;
}
运行结果:
原图:
修改后:
思维导图: