Files: c52a3123eba4e4c49aabce41af35e284092287ad / pngspark.c
1904 bytesRaw
1 | |
2 | |
3 | |
4 | |
5 | |
6 | |
7 | |
8 | |
9 | static const size_t initial_size = 8; |
10 | |
11 | uint32_t parse_color(const char *color_str) |
12 | { |
13 | if (!color_str) return 0; |
14 | if (color_str[0] == '#') color_str++; |
15 | uint32_t color = strtol(color_str, NULL, 16); |
16 | return 0xff000000 | |
17 | ((color >> 16) | (color & 0x00ff00) | (color & 0xff) << 16); |
18 | } |
19 | |
20 | int pngspark_init(struct pngspark *ps, size_t height, const char *color) |
21 | { |
22 | ps->size = initial_size; |
23 | ps->num_values = 0; |
24 | ps->values = malloc(initial_size * sizeof(double)); |
25 | if (!ps->values) return 1; |
26 | ps->color = parse_color(color); |
27 | ps->height = height; |
28 | ps->max_value = 0; |
29 | return 0; |
30 | } |
31 | |
32 | int pngspark_append(struct pngspark *ps, double value) |
33 | { |
34 | size_t i = ps->num_values++; |
35 | if (i >= ps->size) { |
36 | ps->values = realloc(ps->values, sizeof(double) * (ps->size <<= 1)); |
37 | if (!ps->values) return 1; |
38 | } |
39 | ps->values[i] = value; |
40 | if (value > ps->max_value) |
41 | ps->max_value = value; |
42 | return 0; |
43 | } |
44 | |
45 | static size_t write_fd(const void *ptr, size_t size, size_t count, |
46 | void *userPtr) |
47 | { |
48 | return fwrite(ptr, size, count, (FILE *)userPtr); |
49 | } |
50 | |
51 | int pngspark_write(struct pngspark *ps, FILE *file) |
52 | { |
53 | size_t height = ps->height; |
54 | size_t width = ps->num_values; |
55 | LuImage *img = luImageCreate(ps->num_values, ps->height, 4, 8); |
56 | if (!img) return 1; |
57 | |
58 | double *values = ps->values; |
59 | uint32_t *pixels = (uint32_t *)img->data; |
60 | uint32_t color = ps->color; |
61 | double height_scale = (double)height / (double)ps->max_value; |
62 | |
63 | for (size_t x = 0; x < width; x++) { |
64 | size_t value = height - (values[x] * height_scale); |
65 | for (size_t y = 0; y < value; y++) |
66 | pixels[x + width * y] = 0; |
67 | for (size_t y = value; y < height; y++) |
68 | pixels[x + width * y] = color; |
69 | } |
70 | |
71 | int ret = luPngWrite(write_fd, file, img); |
72 | luImageRelease(img); |
73 | return ret; |
74 | } |
75 | |
76 | int pngspark_end(struct pngspark *ps) |
77 | { |
78 | free(ps->values); |
79 | return 0; |
80 | } |
81 | |
82 |
Built with git-ssb-web