If you deal with graphics, sometimes you want to get the number of colors used in a bitmap. Call CountColors() passing the TBitmap to return an integer value. This code was adapted from Earl F. Glynn.
// Count number of unique R-G-B triples in a pf24bit Bitmap only. // Code adapted from Earl F. Glynn // email: [email protected] // web page: http://www.efg2.com/lab/ function CountColors(const Bitmap: TBitmap): integer; type pRGBTripleArray = ^TRGBTripleArray; TRGBTripleArray = array[0..MaxPixelCount-1] of TRGBTriple; var Flags: array[byte, byte] of TBits;
i, j,k: integer; rowIn: pRGBTripleArray; begin // Be sure bitmap is 24-bits/pixel assert(Bitmap.PixelFormat = pf24Bit); // Clear 2D array of TBits objects for j := 0 to 255 do for i := 0 to 255 do Flags[i,j] := nil; // Step through each scanline of image for j := 0 to Bitmap.Height-1 do begin rowIn := Bitmap.Scanline[j]; for i := 0 to Bitmap.Width-1 do with rowIn[i] do begin ifnot Assigned(Flags[rgbtRed, rgbtGreen]) then begin // Create 3D column when needed Flags[rgbtRed, rgbtGreen] := TBits.Create; Flags[rgbtRed, rgbtGreen].Size := 256; end; // Mark this R-G-B triple Flags[rgbtRed,rgbtGreen].Bits[rgbtBlue] := True; end; end; Result := 0; // Count and Free TBits objects for j := 0 to 255 do for i := 0 to 255 do if Assigned(Flags[i,j]) then begin for k := 0 to 255 do if Flags[i,j].Bits[k] then Inc(Result); Flags[i,j].Free; end; end;