Files: 16f492a7668162cda0aa59a56f6efbe644b19295 / pngspark.c
1992 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 | int pngspark_draw(struct pngspark *ps, uint32_t *data, size_t width, |
46 | size_t height) |
47 | { |
48 | double *values = ps->values; |
49 | uint32_t color = ps->color; |
50 | double height_scale = (double)height / (double)ps->max_value; |
51 | for (size_t x = 0; x < width; x++) { |
52 | size_t value = values[x] * height_scale; |
53 | for (size_t y = 0; y < value; y++) |
54 | data[x + width * y] = 0; |
55 | for (size_t y = value; y <= height; y++) |
56 | data[x + width * y] = color; |
57 | } |
58 | return 0; |
59 | } |
60 | |
61 | static size_t write_fd(const void *ptr, size_t size, size_t count, |
62 | void *userPtr) |
63 | { |
64 | return fwrite(ptr, size, count, (FILE *)userPtr); |
65 | } |
66 | |
67 | int pngspark_write(struct pngspark *ps, FILE *file) |
68 | { |
69 | LuImage *img = luImageCreate(ps->num_values, ps->max_value+1, 4, 8); |
70 | if (!img) return 1; |
71 | |
72 | int ret = pngspark_draw(ps, (uint32_t *)img->data, ps->num_values, |
73 | ps->max_value); |
74 | if (!ret) |
75 | ret = luPngWrite(write_fd, file, img); |
76 | luImageRelease(img); |
77 | return ret; |
78 | } |
79 | |
80 | int pngspark_end(struct pngspark *ps) |
81 | { |
82 | free(ps->values); |
83 | return 0; |
84 | } |
85 | |
86 |
Built with git-ssb-web