Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include "linkedlist.h"
- #define MAX_COMMENT_LENGTH 256
- #define MAX_COMMENTS 100
- #define MAX_IMAGE_WIDTH 600
- #define MAX_IMAGE_HEIGHT 600
- struct Pixel {
- int r;
- int g;
- int b;
- } Pixel;
- struct PPM {
- char format[2 + 1]; //2 letter code for PPM format, +1 for 2 spaces
- List *comments;
- int width; //number of columns
- int height; //number of rows
- int max; //maximum colour value (usually 255)
- struct Pixel **rgb;
- } PPM;
- struct PPM * getPPM(FILE *fd);
- void showPPM(struct PPM *i);
- int main() {
- FILE *file = fopen("black.ppm", "r");
- if(file == NULL) return 1;
- else {
- struct PPM *newPPM = getPPM(file);
- showPPM(newPPM);
- }
- return 0;
- }
- struct PPM * getPPM(FILE *fd) {
- if(fd == NULL) {
- perror("File does not exist!");
- return NULL;
- }
- struct PPM *newPPMFile = malloc(sizeof(PPM));
- List *commentList = List_create();
- fscanf(fd, "%2c\n", newPPMFile->format);
- newPPMFile->format[2] = '\0'; //Need to end the string with \0
- //printf("%s\n", newPPMFile->format);
- char comment[MAX_COMMENTS][MAX_COMMENT_LENGTH];
- int i = 0;
- while(fscanf(fd, "# %79[^\n] \n", comment[i]) == 1) {
- comment[i][MAX_COMMENT_LENGTH - 1] = '\0';
- List_append(commentList, comment[i]);
- i++;
- }
- newPPMFile->comments = commentList;
- //List_print(newPPMFile->comments);
- //Read width and height
- if (fscanf(fd, "%d %d", &newPPMFile->width, &newPPMFile->height) != 2) {
- perror("Error reading width and height!");
- return NULL; //Error
- }
- //printf("%d %d\n", newPPMFile->width, newPPMFile->height);
- //Read max rgb value
- if(fscanf(fd, "%d", &newPPMFile->max) != 1) {
- perror("Error reading max colour value!");
- return NULL; //Error
- }
- //printf("%d\n", newPPMFile->max);
- //new array of width rows, height columns
- struct Pixel rgbArray[newPPMFile->height][newPPMFile->width];
- int x, y;
- for(y = 0; y < newPPMFile->height; y++) {
- for(x = 0; x < newPPMFile->width; x++) {
- struct Pixel newPixel;
- if (fscanf(fd, "%d%d%d\n", &newPixel.r, &newPixel.g, &newPixel.b) == 3) {
- rgbArray[y][x] = newPixel;
- //printf("%d %d %d\n", rgbArray[y][x].r, rgbArray[y][x].g, rgbArray[y][x].b);
- } else {
- //Handle error...
- perror("NO RGB??");
- }
- }
- }
- newPPMFile->rgb = rgbArray;
- return newPPMFile;
- }
- void showPPM(struct PPM *i) {
- /* Print PPM format */
- printf("%s\n", i->format);
- /* Print comments */
- List_print(i->comments);
- /* Print width and height */
- printf("%d %d\n", i->width, i->height);
- /* Print max rgb value */
- printf("%d\n", i->max);
- int x, y;
- for(y = 0; y < i->height; y++) {
- for(x = 0; x < i->width; x++) {
- struct Pixel newPixel = i->rgb[y][x];
- printf("%d %d %d\n", newPixel.r, newPixel.g, newPixel.b);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement