unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, jpeg; type TForm1 = class(TForm) Image1: TImage; Button1: TButton; procedure Button1Click(Sender: TObject); private { Déclarations privées } public { Déclarations publiques } end; var Form1: TForm1; type TRGBA = packed record B: Byte; G: Byte; R: Byte; A: Byte; end; type TRGBAArray = packed array[0..MaxInt div SizeOf(TRGBA) - 1] of TRGBA; type PRGBAArray = ^TRGBAArray; // On va utiliser qsort de msvcrt pour trier les couleurs type TComparatorFunction = function(lpItem1: Pointer; lpItem2: Pointer): Integer; cdecl; procedure qsort(base: Pointer; num: Cardinal; size: Cardinal; lpComparatorFunction: TComparatorFunction) cdecl; external 'msvcrt.dll'; implementation {$R *.dfm} function PixelComparator(lpItem1: Pointer; lpItem2: Pointer): Integer; cdecl; var lpPixel1: ^Cardinal; lpPixel2: ^Cardinal; begin lpPixel1:= lpItem1; lpPixel2:= lpItem2; Result:= lpPixel1^ - lpPixel2^; end; procedure TForm1.Button1Click(Sender: TObject); var x, y, i: Integer; lpLine: PRGBAArray; lpPixels: Array of TRGBA; nPixelCount: Integer; nColorsCount: Integer; previousColor: TRGBA; begin with Image1.Picture.Bitmap do begin nPixelCount:= Width * Height; SetLength(lpPixels, nPixelCount); PixelFormat:= pf32bit; // On stocks tous les pixels de la bitmap dans lpPixels i:= 0; for y:= 0 to Height - 1 do begin lpLine:= Scanline[y]; for x:= 0 to Width - 1 do begin lpPixels[i]:= lpLine[x]; Inc(i); end; end; end; // On trie les pixels qsort(lpPixels, nPixelCount, SizeOf(TRGBA), PixelComparator); // Pour le fun, on met à jour l'image avec les valeurs triées with Image1.Picture.Bitmap do begin i:= 0; for y:= 0 to Height - 1 do begin lpLine:= Scanline[y]; for x:= 0 to Width - 1 do begin lpLine[x]:= lpPixels[i]; Inc(i); end; end; end; Image1.Invalidate; // On parcourt le tableau trier pour compter les uniques nColorsCount:= 1; previousColor:= lpPixels[0]; for i:= 1 to nPixelCount - 1 do begin if Cardinal(lpPixels[i]) <> Cardinal(previousColor) then begin Inc(nColorsCount); previousColor:= lpPixels[i]; end; end; ShowMessage('Il y a ' + IntToStr(nColorsCount) + ' couleurs différentes dans cette image.'); end; end.
Vous n’avez pas trouvé la réponse que vous recherchez ?
Posez votre questioncorriger le code suivant