Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define min(a,b) ((a) < (b) ? (a) : (b))
- #define max(a,b) ((a) > (b) ? (a) : (b))
- struct img {
- size_t w, h;
- size_t area;
- size_t size;
- unsigned char buf[];
- };
- static struct img*
- img_new(size_t w, size_t h)
- {
- const size_t size = sizeof(struct img) + w * h * 3;
- struct img *img = mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
- img->w = w, img->h = h;
- img->area = img->w * img->h;
- img->size = img->area * 3;
- return img;
- }
- static void
- img_del(struct img *img)
- {
- if (!img) return;
- munmap(img, sizeof(struct img) + img->w * img->h * 3);
- }
- static void
- img_write(FILE *fp, const struct img *img)
- {
- fprintf(fp, "P6\n%zu %zu\n255\n", img->w, img->h);
- fwrite(img->buf, img->area, 3, fp);
- fflush(fp);
- }
- static struct img*
- img_resize(struct img *img, size_t w, size_t h)
- {
- if (!img || img->w != w || img->h != h) {
- img_del(img);
- img = img_new(w,h);
- }
- return img;
- }
- static struct img*
- img_read(struct img *img, FILE *fp)
- {
- size_t w, h;
- if (fscanf(fp, "P6 %zu %zu%*d%*c", &w, &h) < 2) {
- img_del(img);
- return 0;
- }
- img = img_resize(img, w, h);
- fread(img->buf, img->area, 3, fp);
- return img;
- }
- static void
- img_get(unsigned char *col, const struct img *img, size_t x, size_t y)
- {
- col[0] = img->buf[y * img->w * 3 + x * 3 + 0];
- col[1] = img->buf[y * img->w * 3 + x * 3 + 1];
- col[2] = img->buf[y * img->w * 3 + x * 3 + 2];
- }
- static void
- img_set(struct img *img, size_t x, size_t y, const unsigned char *col)
- {
- img->buf[y * img->w * 3 + x * 3 + 0] = col[0];
- img->buf[y * img->w * 3 + x * 3 + 1] = col[1];
- img->buf[y * img->w * 3 + x * 3 + 2] = col[2];
- }
- static void
- join(void)
- {
- pid_t wpid;
- int status = 0;
- while ((wpid = wait(&status)) > 0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement