xref: /PHP-8.4/ext/gd/libgd/gd_color_match.c (revision f8202b55)
1 #include "gd.h"
2 #include "gdhelpers.h"
3 
4 #include "gd_intern.h"
5 #include "php.h"
6 
7 /* bring the palette colors in im2 to be closer to im1
8  *
9  */
gdImageColorMatch(gdImagePtr im1,gdImagePtr im2)10 int gdImageColorMatch (gdImagePtr im1, gdImagePtr im2)
11 {
12 	unsigned long *buf; /* stores our calculations */
13 	unsigned long *bp; /* buf ptr */
14 	int color, rgb;
15 	int x,y;
16 	int count;
17 
18 	if( !im1->trueColor ) {
19 		return -1; /* im1 must be True Color */
20 	}
21 	if( im2->trueColor ) {
22 		return -2; /* im2 must be indexed */
23 	}
24 	if( (im1->sx != im2->sx) || (im1->sy != im2->sy) ) {
25 		return -3; /* the images are meant to be the same dimensions */
26 	}
27 	if (im2->colorsTotal<1) {
28 		return -4; /* At least 1 color must be allocated */
29 	}
30 
31 	buf = (unsigned long *)safe_emalloc(sizeof(unsigned long), 5 * gdMaxColors, 0);
32 	memset( buf, 0, sizeof(unsigned long) * 5 * gdMaxColors );
33 
34 	for (x=0; x<im1->sx; x++) {
35 		for( y=0; y<im1->sy; y++ ) {
36 			color = im2->pixels[y][x];
37 			rgb = im1->tpixels[y][x];
38 			bp = buf + (color * 5);
39 			(*(bp++))++;
40 			*(bp++) += gdTrueColorGetRed(rgb);
41 			*(bp++) += gdTrueColorGetGreen(rgb);
42 			*(bp++) += gdTrueColorGetBlue(rgb);
43 			*(bp++) += gdTrueColorGetAlpha(rgb);
44 		}
45 	}
46 	bp = buf;
47 	for (color=0; color<im2->colorsTotal; color++) {
48 		count = *(bp++);
49 		if( count > 0 ) {
50 			im2->red[color]		= *(bp++) / count;
51 			im2->green[color]	= *(bp++) / count;
52 			im2->blue[color]	= *(bp++) / count;
53 			im2->alpha[color]	= *(bp++) / count;
54 		} else {
55 			bp += 4;
56 		}
57 	}
58 	gdFree(buf);
59 	return 0;
60 }
61 
62 
63