-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage.c
87 lines (74 loc) · 2.88 KB
/
image.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
#include "image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image/stb_image_write.h"
// Sets the RGP values of the pixel at the given position on the image
void colorPixel(int width, int height, Pixel_t image[width][height], int x, int y, int r, int g, int b) {
image[x][y].Red = r;
image[x][y].Green = g;
image[x][y].Blue = b;
}
// Colors the background of the image
void colorBackground(int width, int height, Pixel_t image[width][height], int r, int g, int b) {
for (int h = 0; h < height; h++) {
for (int w = 0; w < width; w++) {
colorPixel(width, height, image, h, w, r, g, b);
}
}
}
// Draws either a vertical or horizontal line
void drawLine(int width, int height, Pixel_t image[width][height], int x1, int y1, int x2, int y2, int r, int g, int b) {
// Vertical
if (x1 - x2 == 0 && y1 - y2 != 0) {
int min_y = MIN(y1, y2);
int max_y = MAX(y1, y2);
for (int y = min_y; y < max_y; y++) {
colorPixel(width, height, image, x1, y, r, g, b);
}
}
// Horizontal
else if (x1 - x2 != 0 && y1 - y2 == 0) {
int min_x = MIN(x1, x2);
int max_x = MAX(x1, x2);
for (int x = min_x; x < max_x; x++) {
colorPixel(width, height, image, x, y1, r, g, b);
}
}
}
// Functions for circle-generation using Bresenham's algorithm
// https://www.geeksforgeeks.org/bresenhams-circle-drawing-algorithm/
void colorCircle(int width, int height, Pixel_t image[width][height], int xc, int yc, int x, int y, int r, int g, int b) {
drawLine(width, height, image, xc+x, yc+y+1, xc+x, yc-y, r, g, b);
drawLine(width, height, image, xc-x, yc+y+1, xc-x, yc-y, r, g, b);
drawLine(width, height, image, xc+y+1, yc+x, xc-y, yc+x, r, g, b);
drawLine(width, height, image, xc+y+1, yc-x, xc-y, yc-x, r, g, b);
}
void drawCircle(int width, int height, Pixel_t image[width][height], int xc, int yc, int radius, int r, int g, int b) {
int x = 0, y = radius;
int d = 3 - 2 * radius;
colorCircle(width, height, image, xc, yc, x, y, r, g, b);
while (y >= x) {
x++;
if (d > 0) {
y--;
d = d + 4 * (x - y) + 10;
}
else {
d = d + 4 * x + 6;
}
colorCircle(width, height, image, xc, yc, x, y, r, g, b);
}
}
// Saves the given image
void saveImage(int width, int height, Pixel_t image[width][height], char* filename) {
BYTE* pure_byte_image = malloc(width * height * BYTES_PER_PIXEL);
int i = -1;
for (int h = 0; h < height; h++) {
for (int w = 0; w < width; w++) {
pure_byte_image[++i] = image[w][h].Red;
pure_byte_image[++i] = image[w][h].Green;
pure_byte_image[++i] = image[w][h].Blue;
}
}
stbi_write_png(filename, width, height, BYTES_PER_PIXEL, pure_byte_image, width * BYTES_PER_PIXEL);
free(pure_byte_image);
}