forked from 61c-teach/fa20-proj1-starter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimageloader.c
97 lines (93 loc) · 2.35 KB
/
imageloader.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/************************************************************************
**
** NAME: imageloader.c
**
** DESCRIPTION: CS61C Fall 2020 Project 1
**
** AUTHOR: Dan Garcia - University of California at Berkeley
** Copyright (C) Dan Garcia, 2020. All rights reserved.
** Justin Yokota - Starter Code
** YOUR NAME HERE
**
**
** DATE: 2020-08-15
**
**************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <string.h>
#include "imageloader.h"
//Opens a .ppm P3 image file, and constructs an Image object.
//You may find the function fscanf useful.
//Make sure that you close the file with fclose before returning.
Image *readData(char *filename)
{
FILE * fp ;
if((fp = fopen(filename,"r") ) == NULL)
{
perror("fopen\n");
exit(-1);
}
char op[2];int cols,rows,Maxp;
fscanf(fp,"%s%d%d%d", op,&cols,&rows,&Maxp);
if(op[0] != 'P' || op[1] != '3' )
{
perror("ppm error\n");
exit(-1);
}
Image* ret = (Image* ) malloc(sizeof (struct Image));
Color** images = (Color**)malloc(sizeof(void*)* rows * cols);
for(int i = 0 ;i < rows ; i++)
for(int j = 0; j<cols ; j++)
{
int r,g,b;
fscanf(fp,"%d%d%d",&r,&g,&b);
if(0<=r && r <= 255 && 0<=g && g<=255 && 0<= b && b<=255)
{
Color* color = (Color *)malloc(sizeof(struct Color));
color->R = (uint8_t)r;
color->G = (uint8_t)g;
color->B = (uint8_t)b;
images[j + i * cols ] = color;
}
else perror("cur range out\n");
}
ret->image = images;
ret->rows = rows;
ret->cols = cols;
fclose(fp);
return ret;
}
//Given an image, prints to stdout (e.g. with printf) a .ppm P3 file with the image's data.
void writeData(Image *image)
{
uint8_t rows = image->rows;
uint8_t cols = image->cols;
Color** colors = image-> image;
printf("%s\n%d %d\n%d\n","P3",cols,rows,255);
for(int i = 0 ; i<rows; i++)
{
for(int j = 0 ; j<cols ;j++)
{
struct Color * color = colors[j + i * cols];
printf("%3u %3u %3u ",color->R,color->G,color->B);
}
putc('\n',stdout);
}
}
//Frees an image
void freeImage(Image *image)
{
Color** colors = image->image;
int rows = image -> rows;
int cols = image -> cols;
for(int i = 0 ;i < rows; i++)
for(int j = 0; j< cols ;j++)
{
struct Color * color = colors[j+ i*cols];
free(color);
}
free(colors);
free(image);
}