Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. #define min(a,b) ((a) < (b) ? (a) : (b))
  2. #define max(a,b) ((a) > (b) ? (a) : (b))
  3.  
  4. struct img {
  5. size_t w, h;
  6. size_t area;
  7. size_t size;
  8. unsigned char buf[];
  9. };
  10. static struct img*
  11. img_new(size_t w, size_t h)
  12. {
  13. const size_t size = sizeof(struct img) + w * h * 3;
  14. struct img *img = mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
  15. img->w = w, img->h = h;
  16. img->area = img->w * img->h;
  17. img->size = img->area * 3;
  18. return img;
  19. }
  20. static void
  21. img_del(struct img *img)
  22. {
  23. if (!img) return;
  24. munmap(img, sizeof(struct img) + img->w * img->h * 3);
  25. }
  26. static void
  27. img_write(FILE *fp, const struct img *img)
  28. {
  29. fprintf(fp, "P6\n%zu %zu\n255\n", img->w, img->h);
  30. fwrite(img->buf, img->area, 3, fp);
  31. fflush(fp);
  32. }
  33. static struct img*
  34. img_resize(struct img *img, size_t w, size_t h)
  35. {
  36. if (!img || img->w != w || img->h != h) {
  37. img_del(img);
  38. img = img_new(w,h);
  39. }
  40. return img;
  41. }
  42. static struct img*
  43. img_read(struct img *img, FILE *fp)
  44. {
  45. size_t w, h;
  46. if (fscanf(fp, "P6 %zu %zu%*d%*c", &w, &h) < 2) {
  47. img_del(img);
  48. return 0;
  49. }
  50. img = img_resize(img, w, h);
  51. fread(img->buf, img->area, 3, fp);
  52. return img;
  53. }
  54. static void
  55. img_get(unsigned char *col, const struct img *img, size_t x, size_t y)
  56. {
  57. col[0] = img->buf[y * img->w * 3 + x * 3 + 0];
  58. col[1] = img->buf[y * img->w * 3 + x * 3 + 1];
  59. col[2] = img->buf[y * img->w * 3 + x * 3 + 2];
  60. }
  61. static void
  62. img_set(struct img *img, size_t x, size_t y, const unsigned char *col)
  63. {
  64. img->buf[y * img->w * 3 + x * 3 + 0] = col[0];
  65. img->buf[y * img->w * 3 + x * 3 + 1] = col[1];
  66. img->buf[y * img->w * 3 + x * 3 + 2] = col[2];
  67. }
  68. static void
  69. join(void)
  70. {
  71. pid_t wpid;
  72. int status = 0;
  73. while ((wpid = wait(&status)) > 0);
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement