xgetshape
view src/image.c @ 2:b832d3b3ed98
taking offset into account in get_window_shape
author | John Tsiombikas <nuclear@member.fsf.org> |
---|---|
date | Mon, 01 Feb 2016 12:18:29 +0200 |
parents | |
children |
line source
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <errno.h>
5 #include "image.h"
7 int image_create(struct image *img, int w, int h)
8 {
9 img->width = w;
10 img->height = h;
11 if(!(img->pixels = malloc(w * h * 4))) {
12 return -1;
13 }
14 return 0;
15 }
17 void image_destroy(struct image *img)
18 {
19 free(img->pixels);
20 img->pixels = 0;
21 }
23 int image_save(struct image *img, const char *rgbname, const char *aname)
24 {
25 int i;
26 FILE *fp;
27 unsigned char *pptr;
29 if(rgbname) {
30 if(!(fp = fopen(rgbname, "wb"))) {
31 fprintf(stderr, "failed to open %s for writing: %s\n", rgbname, strerror(errno));
32 return -1;
33 }
35 fprintf(fp, "P6\n%d %d\n255\n", img->width, img->height);
36 pptr = img->pixels;
37 for(i=0; i<img->width * img->height; i++) {
38 fputc(*pptr++, fp);
39 fputc(*pptr++, fp);
40 fputc(*pptr++, fp);
41 ++pptr;
42 }
43 fclose(fp);
44 }
45 if(aname) {
46 if(!(fp = fopen(aname, "wb"))) {
47 fprintf(stderr, "failed to open %s for writing: %s\n", rgbname, strerror(errno));
48 return -1;
49 }
51 fprintf(fp, "P6\n%d %d\n255\n", img->width, img->height);
52 pptr = img->pixels;
53 for(i=0; i<img->width * img->height; i++) {
54 int c = pptr[3];
55 pptr += 4;
56 fputc(c, fp);
57 fputc(c, fp);
58 fputc(c, fp);
59 }
60 fclose(fp);
61 }
62 return 0;
63 }
65 int image_clear(struct image *img, int r, int g, int b, int a)
66 {
67 return image_fillrect(img, 0, 0, img->width, img->height, r, g, b, a);
68 }
70 int image_fillrect(struct image *img, int x, int y, int w, int h, int r, int g, int b, int a)
71 {
72 int i, j;
73 unsigned char *pptr;
75 if(x < 0) {
76 w += x;
77 x = 0;
78 }
79 if(y < 0) {
80 h += y;
81 y = 0;
82 }
83 if(x + w >= img->width) {
84 w = img->width - x;
85 }
86 if(y + h >= img->height) {
87 h = img->height - y;
88 }
89 if(w <= 0 || h <= 0) {
90 return -1;
91 }
93 pptr = img->pixels + (y * img->width + x) * 4;
94 for(i=0; i<h; i++) {
95 for(j=0; j<w; j++) {
96 pptr[0] = r;
97 pptr[1] = g;
98 pptr[2] = b;
99 pptr[3] = a;
100 pptr += 4;
101 }
102 pptr += (img->width - w) * 4;
103 }
104 return 0;
105 }
107 int image_chess(struct image *img, int sz, int r0, int g0, int b0, int r1, int g1, int b1)
108 {
109 int i, j;
110 unsigned char *pptr = img->pixels;
112 for(i=0; i<img->height; i++) {
113 for(j=0; j<img->width; j++) {
114 int chess = ((i / sz) & 1) == ((j / sz) & 1);
115 *pptr++ = chess ? r0 : r1;
116 *pptr++ = chess ? g0 : g1;
117 *pptr++ = chess ? b0 : b1;
118 *pptr++ = 255;
119 }
120 }
121 return 0;
122 }