/* ppm filter library by kumagai masaaki*/ /* as example of xv algorithm extension */ #include #include #include #include typedef unsigned char imgbyte; int DEBUG=0; void Exchange(int *a,int *b) { int t; t=*a; *a= *b; *b=t; } void RegulatePos(int w,int h,int *sx,int *sy,int *ex,int *ey) { if(*sx<0) *sx=0; if(*sy<0) *sy=0; if(*ex<0) *ex=w-1; if(*ey<0) *ey=h-1; if(*ex>w-1) *ex=w-1; if(*ey>h-1) *ey=h-1; if(*sx>*ex) Exchange(sx,ex); if(*sy>*ey) Exchange(sy,ey); } /* PPM FILE load */ imgbyte* LoadPPM(FILE *fp,int *_w,int *_h,int *_max) { char buff[1000]; char magic[10]; int w,h,max; imgbyte *data; int i,j; fgets(buff,1000,fp); if((buff[0]!='P')||((buff[1]!='3')&&(buff[1]!='6'))) { fprintf(stderr,"PPM format error \n"); return NULL; } while(sscanf(buff,"%s %d %d %d",magic,&w,&h,&max)!=4) { fgets(buff+strlen(buff),990-strlen(buff),fp); if(strlen(buff)>900) { fprintf(stderr,"PPM format error\n"); fclose(fp); } if(strchr(buff,'#')) *(strchr(buff,'#'))='\0'; } if(DEBUG) fprintf(stderr,"image size %dx%d\n",w,h); data=(imgbyte *)malloc(w*h*3); if(data==NULL) { fprintf(stderr,"cannot alloc memory\n"); return NULL; } if(magic[1]=='6') /* RAW mode */ { if(fread(data,w*3,h,fp)!=h) { fprintf(stderr,"PPM size error\n"); free(data); return NULL; } *_w=w; *_h=h; *_max=max; return data; } /* ASCII mode : does this work any time? */ for(i=0;i900) { fprintf(stderr,"PPM format error\n"); fclose(fp); } if(strchr(buff,'#')) *(strchr(buff,'#'))='\0'; } if(DEBUG) fprintf(stderr,"image size %dx%d\n",w,h); data=(imgbyte *)malloc(w*h); if(data==NULL) { fprintf(stderr,"cannot alloc memory\n"); return NULL; } if(magic[1]=='5') /* RAW mode */ { if(fread(data,w,h,fp)!=h) { fprintf(stderr,"PPM size error\n"); free(data); return NULL; } *_w=w; *_h=h; *_max=max; return data; } /* ASCII mode : does this work any time? */ for(i=0;i255) max=255; if(max<0) max=0; fprintf(fp,"P6\n%d %d\n%d\n",ex-sx+1,ey-sy+1,max); for(y=sy;y<=ey;y++) fwrite(data+(y*w+sx)*3,3,ex-sx+1,fp); fclose(fp); } /* PGM File save */ int SavePGM(FILE *fp, imgbyte *data,int max, int w,int h,int sx,int sy,int ex,int ey) { int y; RegulatePos(w,h,&sx,&sy,&ex,&ey); if(max>255) max=255; if(max<0) max=0; fprintf(fp,"P5\n%d %d\n%d\n",ex-sx+1,ey-sy+1,max); for(y=sy;y<=ey;y++) fwrite(data+(y*w+sx),1,ex-sx+1,fp); fclose(fp); }