public int pixelFromRGB(int red, int green, int blue, ColorModel cm) {
    if (is888()) {
      return (red << redShift) | (green << greenShift) | (blue << blueShift);
    } else if (trueColour) {
      int r = (red   * redMax     + 127) / 255;
      int g = (green * greenMax   + 127) / 255;
      int b = (blue  * blueMax    + 127) / 255;

      return (r << redShift) | (g << greenShift) | (b << blueShift);
    } else if (cm != null) {
      // Try to find the closest pixel by Cartesian distance
      int colours = 1 << depth;
      int diff = 256 * 256 * 4;
      int col = 0;
      for (int i = 0; i < colours; i++) {
        int r, g, b;
        r = cm.getRed(i);
        g = cm.getGreen(i);
        b = cm.getBlue(i);
        int rd = (r - red) >> 8;
        int gd = (g - green) >> 8;
        int bd = (b - blue) >> 8;
        int d = rd * rd + gd * gd + bd * bd;
        if (d < diff) {
          col = i;
          diff = d;
        }
      }
      return col;
    }
    // XXX just return 0 for colour map?
    return 0;
  }