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