+\f
+/* Image background colors. */
+
+static unsigned long
+four_corners_best (ximg, width, height)
+ XImage *ximg;
+ unsigned long width, height;
+{
+ unsigned long corners[4], best;
+ int i, best_count;
+
+ /* Get the colors at the corners of ximg. */
+ corners[0] = XGetPixel (ximg, 0, 0);
+ corners[1] = XGetPixel (ximg, width - 1, 0);
+ corners[2] = XGetPixel (ximg, width - 1, height - 1);
+ corners[3] = XGetPixel (ximg, 0, height - 1);
+
+ /* Choose the most frequently found color as background. */
+ for (i = best_count = 0; i < 4; ++i)
+ {
+ int j, n;
+
+ for (j = n = 0; j < 4; ++j)
+ if (corners[i] == corners[j])
+ ++n;
+
+ if (n > best_count)
+ best = corners[i], best_count = n;
+ }
+
+ return best;
+}
+
+/* Return the `background' field of IMG. If IMG doesn't have one yet,
+ it is guessed heuristically. If non-zero, XIMG is an existing XImage
+ object to use for the heuristic. */
+
+unsigned long
+image_background (img, f, ximg)
+ struct image *img;
+ struct frame *f;
+ XImage *ximg;
+{
+ if (! img->background_valid)
+ /* IMG doesn't have a background yet, try to guess a reasonable value. */
+ {
+ int free_ximg = !ximg;
+
+ if (! ximg)
+ ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
+ 0, 0, img->width, img->height, ~0, ZPixmap);
+
+ img->background = four_corners_best (ximg, img->width, img->height);
+
+ if (free_ximg)
+ XDestroyImage (ximg);
+
+ img->background_valid = 1;
+ }
+
+ return img->background;
+}
+
+/* Return the `background_transparent' field of IMG. If IMG doesn't
+ have one yet, it is guessed heuristically. If non-zero, MASK is an
+ existing XImage object to use for the heuristic. */
+
+int
+image_background_transparent (img, f, mask)
+ struct image *img;
+ struct frame *f;
+ XImage *mask;
+{
+ if (! img->background_transparent_valid)
+ /* IMG doesn't have a background yet, try to guess a reasonable value. */
+ {
+ if (img->mask)
+ {
+ int free_mask = !mask;
+
+ if (! mask)
+ mask = XGetImage (FRAME_X_DISPLAY (f), img->mask,
+ 0, 0, img->width, img->height, ~0, ZPixmap);
+
+ img->background_transparent
+ = !four_corners_best (mask, img->width, img->height);
+
+ if (free_mask)
+ XDestroyImage (mask);
+ }
+ else
+ img->background_transparent = 0;
+
+ img->background_transparent_valid = 1;
+ }
+
+ return img->background_transparent;
+}