/* Implementation of ppm_image.h */ /* Last edited on 2004-11-07 02:05:38 by stolfi */ #include #include #include #include #include ppm_image *new_ppm_image(int cols, int rows) { ppm_image *img = (ppm_image *)malloc(sizeof(ppm_image)); assert(img != NULL); img->cols = cols; img->rows = rows; if ((cols == 0) || (rows == 0)) { img->pix = (pixel**)NULL; } else { img->pix = alloc_ppm_pixels(cols, rows); } return(img); } void free_ppm_image(ppm_image *img) { if (img == NULL) return; free_ppm_pixels(img->pix, img->cols, img->rows); free(img); } pixel **alloc_ppm_pixels(int cols, int rows) { int row; pixel **pix = (pixel**)malloc(rows*sizeof(pixel*)); if (pix == (pixel**)NULL) pm_error("out of memory"); for (row = 0; row < rows; row++) { if (cols == 0) { pix[row] = (pixel*)NULL; } else { pix[row] = (pixel*)malloc(cols*sizeof(pixel)); if (pix[row] == (pixel*)NULL) pm_error("out of memory"); } } return pix; } void free_ppm_pixels(pixel **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); } ppm_image *read_ppm_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); } ppm_image *img = fread_ppm_image(rd); if (rd != stdin) { pm_close(rd); } return img; } ppm_image *fread_ppm_image(FILE *rd) { ppm_image *img = new_ppm_image(0,0); img->pix = ppm_readppm(rd, &(img->cols), &(img->rows), &(img->maxval)); return(img); } void write_ppm_image(char *name, ppm_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_ppm_image(wr, img, forceplain); if (wr != stdout) { pm_close(wr); } } void fwrite_ppm_image(FILE *wr, ppm_image *img, int forceplain) { int row; ppm_writeppminit(wr, img->cols, img->rows, img->maxval, forceplain); for (row = 0; row < img->rows; row++) { ppm_writeppmrow(wr, img->pix[row], img->cols, img->maxval, forceplain); } fflush(wr); }