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