Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _CRT_SECURE_NO_WARNINGS
- #include <stdio.h>
- #include <stdlib.h>
- #include <ctype.h>
- struct obr_pgm{
- unsigned short int h, w, maxval;
- unsigned short int **dane;
- };
- void free_img(struct obr_pgm **img){
- int i;
- if(*img==NULL) return;
- if((*img)->dane!=NULL){
- for(i=0;i<(*img)->h;i++){
- free((*img)->dane[i]);
- }
- free((*img)->dane);
- free(*img);
- *img=NULL;
- }
- }
- struct obr_pgm *createImg(unsigned short int w, unsigned short int h, unsigned short int maxval){
- struct obr_pgm *retImg;
- int i;
- retImg=(struct obr_pgm*)calloc(1,sizeof(struct obr_pgm));
- if(retImg=NULL) return NULL;
- printf("%d \n%d \n%d \n",w,h,maxval);
- retImg->w=w;
- retImg->h=h;
- retImg->maxval=maxval;
- retImg->dane=(unsigned short int**)calloc(h,sizeof(unsigned short int*));
- if(retImg->dane==NULL){
- free_img(&retImg);
- return NULL;
- }
- for(i=0;i<h;i++){
- retImg->dane[i]=(unsigned short int*)malloc(w*sizeof(unsigned short int));
- if(retImg->dane[i]==NULL){
- free_img(&retImg);
- return NULL;
- }
- }
- return retImg;
- }
- void SkipCom(FILE *f){
- char zn, buff[255];
- zn=fgetc(f);
- do{
- if(zn=='#') fgets(buff,sizeof(buff),f);
- zn=getc(f);
- }while(!isdigit(zn));
- ungetc(zn,f);
- }
- struct obr_pgm *LoadImg(char *path){
- FILE *f;
- char buff[255];
- int w,h,maxval,x,y;
- struct obr_pgm *ptr;
- f=fopen(path,"rt");
- if(f==NULL) return NULL;
- if(fscanf(f,"%2s",buff)!=1){
- fclose(f);
- return NULL;
- }
- if(buff[0]!='P' || (buff[1]!='2' && buff[2]!='5')){
- fclose(f);
- return NULL;
- }
- SkipCom(f);
- if(fscanf(f,"%d %d", &w, &h)!=2){
- fclose(f);
- return NULL;
- }
- SkipCom(f);
- if(fscanf(f,"%d",&maxval)!=1){
- fclose(f);
- return NULL;
- }
- ptr=createImg(w,h,maxval);
- if(ptr==NULL){
- fclose(f);
- return NULL;
- }
- for(y=0;y<h;y++){
- SkipCom(f);
- for(x=0;x<w;x++){
- if(fscanf(f,"%d",&(ptr->dane[y][x]))!=1){
- free(&ptr);
- fclose(f);
- return NULL;
- }
- }
- }
- fclose(f);
- return ptr;
- }
- struct obr_pgm *zapis(struct obr_pgm *ptr, char *path){
- FILE *f;
- int x,y;
- f=fopen(path,"wt");
- if(f==NULL) return NULL;
- fprintf(f, "P2\n");
- fprintf(f, "%d %d\n%d\n", ptr->w, ptr->h, ptr->maxval);
- for(y=0;y<ptr->h;y++){
- for(x=0;x<ptr->w;x++){
- fprintf(f,"%d ",&(ptr->dane[y][x]));
- }
- fprintf(f,"\n");
- }
- fclose(f);
- }
- struct obr_pgm *inwersja(struct obr_pgm *img){
- struct obr_pgm *ptr;
- int x,y;
- if(img==NULL) return NULL;
- ptr=createImg(img->w, img->h,img->maxval);
- if(ptr==NULL) return NULL;
- for(y=0;y<img->h;y++){
- for(x=0;x<img->w;x++){
- ptr->dane[y][x]=img->maxval-(img->dane[y][x]);
- }
- }
- return ptr;
- }
- int main(){
- struct obr_pgm *ptr;
- ptr=LoadImg("bird.pgm");
- inwersja(ptr);
- zapis(ptr,"obrazek.pgm");
- free_img(&ptr);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement