www.pudn.com > GaitRsystem.rar > pgm.cpp


/////////////////////////////////////////////////////////
//  PGM library by Daniel Switkin, utilities@switkin.com
//  Last revised: 5/01/99
//
//  You may do anything you like with this but you must
//  leave this comment in the source, and preferably
//  drop me an email if you use it.
/////////////////////////////////////////////////////////

#include 
#include 
#include 
#include "pgm.h"

PGM::PGM() {
	width = height = 0;
	data = NULL;
}

bool PGM::New(char *name, int width, int height) {
	this->width = width;
	this->height = height;
	strcpy(this->name, name);
	
    if ((data = (unsigned char **)malloc(height * 4)) == NULL) {
		printf("Out of memory\n");
        return false;
    }
	for (int y = 0; y < height; y++) {
		data[y] = new unsigned char[width];
		if (data[y] == NULL) {
			printf("Out of memory\n");
    	    for (int x = 0; x < y; x++) {
    	    	delete data[x];
    	    }
    	    free(data);
        	return false;
    	}
	}
	
	for ( y = 0; y < height; y++) {
    	for (int x = 0; x < width; x++) {
    		data[y][x] = 0;
    	}
    }
		
    return true;
}

bool PGM::Save() {
	FILE *fp;
	if ((fp = fopen(name, "rb")) == NULL) {
		printf("Failed to open %s\n", name);
		return false;
	}
	
	fprintf(fp, "P5\n%d %d\n255\n", width, height);
	for (int y = 0; y < height; y++) {
		fwrite(data[y], width, 1, fp);
	}
	fclose(fp);
	return true;
}

bool PGM::Load(char *name) {
	FILE *fp;
    strcpy(this->name, name);
    if ((fp = fopen(name, "rb")) == NULL) {
        printf("Failed to open %s\n", name);
        return false;
    }
    
    char temp[255];
	// magic number
    fgets(temp, 255, fp);
    if (strstr(temp, "P5") == NULL) {
    	printf("Unsupported file type\n");
    	fclose(fp);
    	return false;
    }
    // hunt for comments
    do {
    	fgets(temp, 255, fp);
    } while (temp[0] == '#');
    
    int max;
    sscanf(temp, "%d %d", &width, &height);
    fscanf(fp, "%d\n", &max);
    printf("File %s has width %d, height %d, max colors %d\n", name, width, height, max);
    
	if ((data = (unsigned char **)malloc(height * 4)) == NULL) {
		printf("Out of memory\n");
        return false;
    }
	for (int y = 0; y < height; y++) {
		data[y] = new unsigned char[width];
		if (data[y] == NULL) {
			printf("Out of memory\n");
    	    for (int x = 0; x < y; x++) {
    	    	delete data[x];
    	    }
    	    free(data);
    	    fclose(fp);
        	return false;
    	}
	}
	
	for ( y = 0; y < height; y++) {
		fread(data[y], width, 1, fp);
	}
	fclose(fp);
	return true;
}

PGM::~PGM() {
    if (data != NULL) {
    	for (int y = 0; y < height; y++) {
    		delete data[y];
    	}
    	free(data);
    }
}