Ejemplo n.º 1
0
void * load_ppm(FILE * fp, unsigned long * xsz, unsigned long * ysz) { // Load P6 PPM
	char buf[64];
	int bytes, raw;
	unsigned int w, h, i, sz;
	uint32_t * pixels;

	rewind(fp);

	bytes = read_to_wspace(fp, buf, 64);
	raw = buf[1] == '6';

	if ((bytes = read_to_wspace(fp, buf, 64)) == 0) {
		fclose(fp);
		return 0;
	}
	if (!isdigit(*buf)) {
		fprintf(stderr, "load_ppm: invalid width: %s\n", buf);
		fclose(fp);
		return 0;
	}
	w = atoi(buf);

	if ((bytes = read_to_wspace(fp, buf, 64)) == 0) {
		fclose(fp);
		return 0;
	}
	if (!isdigit(*buf)) {
		fprintf(stderr, "load_ppm: invalid height: %s\n", buf);
		fclose(fp);
		return 0;
	}
	h = atoi(buf);

	if ((bytes = read_to_wspace(fp, buf, 64)) == 0) {
		fclose(fp);
		return 0;
	}
	if (!isdigit(*buf) || atoi(buf) != 255) {
		fprintf(stderr, "load_ppm: invalid or unsupported max value: %s\n",
				buf);
		fclose(fp);
		return 0;
	}

	if (!(pixels = new uint32_t[w * h])) {
		fprintf(stderr, "Memory allocation failed\n");
		fclose(fp);
		return 0;
	}

	sz = h * w; // size of image
	for (i = 0; i < sz; i++) {
		int r = fgetc(fp);
		int g = fgetc(fp);
		int b = fgetc(fp);

		if (r == -1 || g == -1 || b == -1) {
			delete[] pixels;
			fclose(fp); // Image is corrupt
			fprintf(stderr, "load_ppm: EOF while reading pixel data\n");
			return 0;
		}
		pixels[i] = PACK_COLOR24(r, g, b);
	}

	fclose(fp);

	if (xsz)
		*xsz = w;
	if (ysz)
		*ysz = h;
	return pixels;
}
Ejemplo n.º 2
0
void *load_ppm(FILE *fp, unsigned long *xsz, unsigned long *ysz) {
	char buf[64];
	int bytes, raw;
	unsigned int w, h, i, sz;
	uint32_t *pixels;
	
	fseek(fp, 0, SEEK_SET);
	
	bytes = read_to_wspace(fp, buf, 64);
	raw = buf[1] == '6';

	if((bytes = read_to_wspace(fp, buf, 64)) == 0) {
		fclose(fp);
		return 0;
	}
	if(!isdigit(*buf)) {
		fprintf(fp, "load_ppm: invalid width: %s", buf);
		fclose(fp);
		return 0;
	}
	w = atoi(buf);

	if((bytes = read_to_wspace(fp, buf, 64)) == 0) {
		fclose(fp);
		return 0;
	}
	if(!isdigit(*buf)) {
		fprintf(fp, "load_ppm: invalid height: %s", buf);
		fclose(fp);
		return 0;
	}
	h = atoi(buf);

	if((bytes = read_to_wspace(fp, buf, 64)) == 0) {
		fclose(fp);
		return 0;
	}
	if(!isdigit(*buf) || atoi(buf) != 255) {
		fprintf(fp, "load_ppm: invalid or unsupported max value: %s", buf);
		fclose(fp);
		return 0;
	}

	if(!(pixels = malloc(w * h * sizeof *pixels))) {
		fputs("malloc failed", fp);
		fclose(fp);
		return 0;
	}

	sz = h * w;
	for(i=0; i<sz; i++) {
		int r = fgetc(fp);
		int g = fgetc(fp);
		int b = fgetc(fp);

		if(r == -1 || g == -1 || b == -1) {
			free(pixels);
			fclose(fp);
			fputs("load_ppm: EOF while reading pixel data", fp);
			return 0;
		}
		pixels[i] = PACK_COLOR24(r, g, b);
	}

	fclose(fp);

	if(xsz) *xsz = w;
	if(ysz) *ysz = h;
	return pixels;
}