/* Implementation of pgm_image.h */ /* Last edited on 2004-11-07 02:04:40 by stolfi */ #include #include #include #include #include pgm_image *new_pgm_image(int cols, int rows) { pgm_image *img = (pgm_image *)malloc(sizeof(pgm_image)); assert(img != NULL); img->cols = cols; img->rows = rows; if ((cols == 0) || (rows == 0)) { img->pix = (pixval**)NULL; } else { img->pix = alloc_pgm_pixels(cols, rows); } return(img); } void free_pgm_image(pgm_image *img) { if (img == NULL) return; free_pgm_pixels(img->pix, img->cols, img->rows); free(img); } pixval** alloc_pgm_pixels(int cols, int rows) { int row; pixval **pix = (pixval**)malloc(rows*sizeof(pixval*)); if (pix == (pixval**)NULL) pm_error("out of memory"); for (row = 0; row < rows; row++) { if (cols == 0) { pix[row] = (pixval*)NULL; } else { pix[row] = (pixval*)malloc(cols*sizeof(pixval)); if (pix[row] == (pixval*)NULL) pm_error("out of memory"); } } return pix; } void free_pgm_pixels(pixval **pix, int cols, int rows) { int row; if (pix == NULL) { return; } for (row = 0; row < rows; row++) { if (pix[row] != NULL) { free(pix[row]); } } free(pix); } pgm_image *read_pgm_image(char *name) { FILE *rd = NULL; if (name == NULL) pm_error("no file name given"); else if (strlen(name) == 0) pm_error("empty file name"); else if (strcmp(name, "-") == 0) { rd = stdin; } else { rd = pm_openr(name); } pgm_image *img = fread_pgm_image(rd); if (rd != stdin) { pm_close(rd); } return img; } pgm_image *fread_pgm_image(FILE *rd) { pgm_image *img = new_pgm_image(0,0); img->pix = pgm_readpgm(rd, &(img->cols), &(img->rows), &(img->maxval)); return(img); } void write_pgm_image(char *name, pgm_image *img, int forceplain) { FILE *wr = NULL; if (name == NULL) pm_error("no file name given"); else if (strlen(name) == 0) pm_error("empty file name"); else if (strcmp(name, "-") == 0) { wr = stdout; } else { wr = pm_openw(name); } fwrite_pgm_image(wr, img, forceplain); if (wr != stdout) { pm_close(wr); } } void fwrite_pgm_image(FILE *wr, pgm_image *img, int forceplain) { int row; pgm_writepgminit(wr, img->cols, img->rows, img->maxval, forceplain); for (row = 0; row < img->rows; row++) { pgm_writepgmrow(wr, img->pix[row], img->cols, img->maxval, forceplain); } fflush(wr); }