Look at MakePaletteForImages for details.
function ImMakePaletteForImages(Images: TImageDataList; Pal: PPalette32; MaxColors: LongInt; ConvertImages: Boolean): Boolean; cdecl;
ImagingExport (at line 131)