-
Notifications
You must be signed in to change notification settings - Fork 26
/
image_utils.c
78 lines (66 loc) · 1.91 KB
/
image_utils.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
#include <stdlib.h>
#include <stdio.h>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
#include "image_utils.h"
Pixel **loadImage(const char *filePath, int *height, int *width) {
int x,y,n;
unsigned char *data = stbi_load(filePath, &x, &y, &n, 4); //4 = force RGBA channels
*height = y;
*width = x;
//contiguous allocation:
Pixel **image = (Pixel **)malloc(sizeof(Pixel *) * y);
image[0] = (Pixel *)malloc(sizeof(Pixel) * (y * x));
for(int i=1; i<y; i++) {
image[i] = (*image + (x * i));
}
int rowIndex = 0;
int colIndex = 0;
for(int i=0; i<(x * y * 4); i+=4) { //for each row
image[rowIndex][colIndex].red = data[i+0];
image[rowIndex][colIndex].green = data[i+1];
image[rowIndex][colIndex].blue = data[i+2];
colIndex++;
if(colIndex == x) {
//go to next row, reset column
rowIndex++;
colIndex=0;
}
}
stbi_image_free(data);
return image;
}
void saveImage(const char *fileName, Pixel **image, int height, int width) {
// Convert height x width Pixel array to single array with
// 3 (RGB) channels, ignoring the alpha channel and assume 100% opaque
unsigned char *data = (unsigned char *) malloc(height * width * 3);
int x = 0;
for(int i=0; i<height; i++) {
for(int j=0; j<width; j++) {
data[x+0] = image[i][j].red;
data[x+1] = image[i][j].green;
data[x+2] = image[i][j].blue;
x+=3;
}
}
//write
stbi_write_jpg(fileName, width, height, 3, data, 100);
free(data);
return;
}
Pixel ** copyImage(Pixel **image, int height, int width) {
//TODO: implement
}
void flipHorizontal(Pixel **image, int height, int width) {
//TODO: implement
return;
}
void flipVertical(Pixel **image, int height, int width) {
//TODO: implement
return;
}
Pixel ** rotateClockwise(Pixel **image, int height, int width) {
//TODO: implement
}