Link to home
Start Free TrialLog in
Avatar of mece
mece

asked on

Convert 24bit grayscale to 8bit image

How can i convert 24 bit grayscale image to 8-bit grayscale image?
24bit image has same rgb values for one pixel.
Avatar of emadat
emadat
Flag of United States of America image

For each pixel in your image,

     Color := Canvas.Pixels[X, Y];
     Gray := Round((0.30 * GetRValue(Color)) + (0.59 * GetGValue(Color)) + (0.11 * GetBValue(Color)));
Sorry it is as follows:

     Color := Canvas.Pixels[X, Y];
     Gray := Round((0.30 * GetRValue(Color)) + (0.59 * GetGValue(Color)) + (0.11 * GetBValue(Color)));
     Color := RGB(Gray, Gray, Gray);
     Canvas.Pixels[X, Y] := Color;
ASKER CERTIFIED SOLUTION
Avatar of DavidRissato
DavidRissato

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of DavidRissato
DavidRissato

You will need to create a gray-scale palette and then copy the original bitmap to there.

I've made a little example below:

procedure TForm1.Button1Click(Sender: TObject);
type
  TLogPal = record
    lpal : TLogPalette;
    colorSpace : Array[0..255] of TPaletteEntry; // This allocate room to
                                                 // new palette colors
                                                 // since palPalEntry member of
                                                 // TLogPalette is declared as
                                                 // Array [0..0] of TPaletteEntry
  end;
var
  bmp : TBitmap;
  pal : TLogPal;
  iCount : integer;
begin
  // Loads the image
  Image1.Picture.LoadFromFile('my_picture.bmp');

  // Create a 256 gray-scale palette
  pal.lpal.palVersion:=$300;
  pal.lpal.palNumEntries := 256;
  for iCount := 0 to 255 do
    with pal.lpal.palPalEntry[iCount] do
      begin
        peRed := iCount;
        peGreen := iCount;
        peBlue := iCount;
      end;

  // Create a temporary bitmap
  bmp := TBitmap.Create;
  try
    // Define bitmap as 8 bit color
    bmp.PixelFormat := pf8bit;

    // Define width and height
    bmp.Width := Image1.Picture.Width;
    bmp.Height := Image1.Picture.Height;

    // Create our new grayscale palette
    bmp.Palette := CreatePalette(pal.lpal);


    // Draw the image on bmp surface
    bmp.Canvas.Draw(0,0,Image1.Picture.Graphic);


    // Save the new 8bit file
    bmp.SaveToFile('my_picture-8bit.bmp');

  finally
    // Free temp bitmap
    bmp.Free;
  end;
end;

{}'s
David Rissato Cruz
Avatar of mece

ASKER

thanx
that is really what i need