Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "ppm.h"
- #include <stdio.h>
- #include <stdlib.h>
- PPM *ppm_alloc(int r, int c) {
- PPM *img;
- img = (PPM *)malloc(sizeof(PPM));
- img->ptype = 6;
- img->w = c;
- img->h = r;
- img->bpp = 3;
- img->max = 255;
- img->name = NULL;
- img->rpix = (float *)malloc(r * c * sizeof(float));
- img->gpix = (float *)malloc(r * c * sizeof(float));
- img->bpix = (float *)malloc(r * c * sizeof(float));
- if (!(img->rpix = (float *)malloc(r * c * sizeof(float)))) {
- fprintf(stderr, "out of memory\n");
- return NULL;
- }
- if (!(img->gpix = (float *)malloc(r * c * sizeof(float)))) {
- fprintf(stderr, "out of memory\n");
- return NULL;
- }
- if (!(img->bpix = (float *)malloc(r * c * sizeof(float)))) {
- fprintf(stderr, "out of memory\n");
- return NULL;
- }
- return img;
- }
- void ppm_free(PPM **img) {
- if ((*img)) {
- if ((*img)->name)
- free((*img)->name);
- if ((*img)->rpix)
- free((*img)->rpix);
- if ((*img)->gpix)
- free((*img)->gpix);
- if ((*img)->bpix)
- free((*img)->bpix);
- free(*img);
- }
- (*img) = NULL;
- }
- PPM *ppm_read(const char *file) {
- int rows = 0, cols = 0, ptype, max;
- unsigned char byte;
- PPM *img;
- FILE *fp;
- if(!(fp = fopen(file, "r"))) {
- fprintf(stderr, "couldn't open file\n");
- return(NULL);
- }
- fscanf(fp, "P%d\n", &ptype);
- fscanf(fp, "%d %d\n", &cols, &rows);
- fscanf(fp, "%d\n", &max);
- if (!(img = ppm_alloc(rows, cols))) {
- fprintf(stderr, "couldn't allocate image\n");
- return (NULL);
- }
- img->h = rows;
- img->w = cols;
- img->max = max;
- img->ptype = ptype;
- for (int i = 0; i < cols; ++i) {
- for (int j = 0; j < rows; ++j) {
- fread(&byte, sizeof(unsigned char), 1, fp);
- img->rpix[i * cols + j] = (float)byte / (float)img->max;
- img->gpix[i * cols + j] = (float)byte / (float)img->max;
- img->bpix[i * cols + j] = (float)byte / (float)img->max;
- }
- }
- fclose(fp);
- return (img);
- }
- void ppm_write(PPM *img, const char *file) {
- int rows = img->h, cols = img->w;
- FILE *fp = fopen(file, "w");
- unsigned char byte;
- fprintf(fp, "P%d\n", img->ptype);
- fprintf(fp, "#made by Lemuel Reid\n");
- fprintf(fp, "%d %d\n", img->w, img->h);
- fprintf(fp, "%d\n", img->max);
- // write pixels
- for (int i = 0; i < rows; i++) {
- for (int j = 0; j < cols; ++j) {
- byte = (unsigned char)(img->rpix[i * img->w + j] * (float)img->max);
- byte = (unsigned char)(img->gpix[i * img->w + j] * (float)img->max);
- byte = (unsigned char)(img->bpix[i * img->w + j] * (float)img->max);
- fwrite(&byte, sizeof(unsigned char), 1, fp);
- }
- }
- fclose(fp);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement