-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathppm.c
74 lines (64 loc) · 1.75 KB
/
ppm.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
/*
* ppm.c
* Řešení IJC-DU1
* Autor: Tomáš Matuš, FIT
* Login: xmatus37
* Datum: 15.3.2021
* Přeloženo: gcc 10.2.0
*/
#include "ppm.h"
#include "error.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// allocate struct for ppm image
struct ppm * ppm_read(const char * filename) {
FILE *fp = fopen(filename, "rb");
if(fp == NULL) {
warning_msg("Chyba otevreni souboru: %s\n", filename);
return NULL;
}
unsigned int xsize, ysize;
// scan header of ppm P6 image
if (fscanf(fp,"P6 %u %u 255 ", &xsize, &ysize) != 2) {
fclose(fp);
warning_msg("Spatna hlavicka obrazku %s!\n", filename);
return NULL;
}
// img size to be allocated
size_t imgSize = xsize * ysize * 3;
if (imgSize > IMG_MAX_SIZE) {
fclose(fp);
warning_msg("Obrazek %s je prilis velky\n", filename);
return NULL;
}
// alloc struct ppm
struct ppm *ppmImg = malloc(sizeof(struct ppm) + imgSize);
if (ppmImg == NULL) {
fclose(fp);
warning_msg("Nepodarilo se alokovat pamet pro obrazek %s\n", filename);
return NULL;
}
ppmImg->xsize = xsize;
ppmImg->ysize = ysize;
// read binary from file and check if real size matches calculated size
if (fread(ppmImg->data, sizeof(char), imgSize, fp) != imgSize) {
fclose(fp);
ppm_free(ppmImg);
warning_msg("Velikost obrazku %s neodpovida rozliseni\n", filename);
return NULL;
}
// check if everything was read
if (fgetc(fp) != EOF) {
fclose(fp);
ppm_free(ppmImg);
warning_msg("Chybne zakonceny soubor\n");
return NULL;
}
fclose(fp);
return ppmImg;
}
// free struct
void ppm_free(struct ppm *p) {
free(p);
}