Source

gd-libgd / src / gd_crop.c

Diff from to

File src/gd_crop.c

 #include <stdlib.h>
 
 static int gdGuessBackgroundColorFromCorners(gdImagePtr im, int *color);
-static int gdColorMatch(gdImagePtr im, int col1, int col2, int threshold);
+static int gdColorMatch(gdImagePtr im, int col1, int col2, float threshold);
 
 BGD_DECLARE(gdImagePtr) gdImageCrop(gdImagePtr src, const gdRect *crop)
 {
 	return gdImageCrop(im, &crop);
 }
 
-BGD_DECLARE(gdImagePtr) gdImageThresholdCrop(gdImagePtr im, const unsigned int color, const int threshold)
+BGD_DECLARE(gdImagePtr) gdImageThresholdCrop(gdImagePtr im, const unsigned int color, const float threshold)
 {
 	const int width = gdImageSX(im);
 	const int height = gdImageSY(im);
 	crop.height = 0;
 
 	/* Pierre: crop everything sounds bad */
-	if (threshold >= 255) {
+	if (threshold > 1.0) {
 		return NULL;
 	}
 
 	}
 }
 
-static int gdColorMatch(gdImagePtr im, int col1, int col2, int threshold)
+static int gdColorMatch(gdImagePtr im, int col1, int col2, float threshold)
 {
-	int diff, max = 0;
+	const int dr = gdImageRed(im, col1) - gdImageRed(im, col2);
+	const int dg = gdImageGreen(im, col1) - gdImageGreen(im, col2);
+	const int db = gdImageBlue(im, col1) - gdImageBlue(im, col2);
+	const int da = gdImageAlpha(im, col1) - gdImageAlpha(im, col2);
+	const int dist = dr * dr + dg * dg + db * db + da * da;
 
-
-	/* alternative method would be to take the distance in the rgb cube
-	 * between the desired color and the current pixel:
-	 * (r2 - r1)^2 + (g2 -b1)^2 + (g1 -g2)^2
-	 *
-	 * but I did not see a difference in my results, that's why I kept
-	 * this faster implementation.
-	 */
-	diff = abs(gdImageRed(im, col2) - gdImageRed(im, col1));
-	if (diff > max) {
-		max = diff;
-	}
-
-	diff = abs(gdImageGreen(im, col2) - gdImageGreen(im, col1));
-	if (diff > max) {
-		max = diff;
-	}
-
-	diff = abs(gdImageBlue(im, col2) - gdImageBlue(im, col1));
-	if (diff > max) {
-		max = diff;
-	}
-/* do we need alpha here? We may detect full transparency and consider
- * them as background
- */
-/*
-	diff = abs(gdImageAlpha(im, col2) - gdImageAlpha(im, col1));
-	if (diff > max) {
-		max = diff;
-	}
-*/
-	return (max < threshold);
+	return (100.0 * dist / 195075) < threshold;
 }
 
 /*