Mega Code Archive

 
Categories / Delphi / Examples
 

Bmpcolourtogreyscale

UNTESTED code of someone else's that references a lookup table to convert between colour and greyscale values, and what do you find? THE LOOKUP TABLE ISN'T THERE procedure CursorBitMapGreyScale; //Working with a pf8bit bitmap requires the use of a pByteArray //to access each pixel in a scanline Row. With this palette //definition in place, the rest of the palette solution is much //like the pf24bit solution. //This example only involves 182 shades of gray, so the limitation //of 236 unique colors in a Windows' palette doesn't affect the image //much. var Bitmap: TBitmap; GrayBuffer: pByteArray; // ARRAY[0..BildWidth-1] OF BYTE; GrayStream: TFileStream; i: INTEGER; j: INTEGER; k: INTEGER; LookupTable: ARRAY[0..255] OF BYTE; Row: pByteArray; // Allocate buffer to read picture file begin GetMem(GrayBuffer, BildWidth); TRY Bitmap := TBitmap.Create; TRY Bitmap.PixelFormat := pf8bit; Bitmap.Width := BildWidth; Bitmap.Height := BildHeight; Bitmap.Palette := DefineShadesOfGrayPalette; GrayStream := TFileStream.Create('Gray.Stream', fmOpenRead); TRY FOR j := 0 TO BildHeight-1 DO BEGIN GrayStream.Read(GrayBuffer^, BildWidth); Row := Bitmap.Scanline[j]; FOR i := 0 TO BildWidth-1 DO BEGIN Row[i] := LookupTable[ GrayBuffer[i] ]; // one byte per pixel END END; // Display image Image.Picture.Graphic := Bitmap; // Save to file Bitmap.SaveToFile('Graypf8bit.BMP'); FINALLY GrayStream.Free; END FINALLY Bitmap.Free; END FINALLY FreeMem(GrayBuffer); end;