1. Home
  2. Computing & Technology
  3. Delphi Programming

Delphi tip: Grayscaling a bitmap

By , About.com Guide

This example uses an averaging mechanism to obtain grayscale intensity on a pixel-by-pixel basis. Specifically, it averages the Red, Green and Blue component values of a color and assigns that value back to each RGB component.

Usage:
GrayScale(Image1.Picture.Graphic, image1.Picture.Bitmap, 0) ;

~~~~~~~~~~~~~~~~~~~~~~~~~
type
   TRGBColor = record
   case Integer of
     0 : (Color : TColor) ;
     1 : (Red, Green, Blue, Intensity : Byte) ;
     2 : (Colors : array[0..3] of Byte) ;
end;

procedure GrayScale(Graphic : TGraphic;
                     Bitmap : TBitmap;
                     Contrast : Integer ) ;
var bmp, mask : TBitmap;
     x, y , Avg : Integer;
     RGBColor : TRGBColor;
begin
   if not Assigned(Graphic) then
     Exit;

   bmp := TBitmap.Create;
   mask := TBitmap.Create;

   try
     bmp.Height := Graphic.Height;
     bmp.Width := Graphic.Width;
     with bmp.Canvas do begin
       if Graphic is TBitmap then
         Brush.Color := (Graphic as TBitmap).TransparentColor
       else
         Brush.Color := clPurple;
       FillRect(ClipRect) ;
       Draw(0,0,Graphic) ;
     end;
     mask.assign(bmp) ;
     mask.mask(bmp.TransparentColor) ;
     with bmp.Canvas do begin
       for y := 0 to ClipRect.Bottom do begin
         for x := 0 to ClipRect.Right do begin
           if mask.Canvas.Pixels[x,y] = clBlack then begin
             RGBColor.Color := Pixels[x,y] ;
             with RGBColor do begin
               Avg := ((Red+Green+Blue) div 3) ;
               Inc(Avg, Contrast) ;
               if Avg > 255 then
                 Avg := 255
               else if Avg < 0 then
                 Avg := 0;
               Red := Avg;
               Green := Avg;
               Blue := Avg;
             end;
             Pixels[x,y] := RGBColor.Color;
           end;
         end;
       end;
     end;
     if Assigned(Bitmap) then
       Bitmap.Assign(bmp)
     else if Graphic is TBitmap then
       (Graphic as TBitmap).Assign(bmp) ;
   finally
     bmp.Free;
     mask.Free;
   end;
end;
~~~~~~~~~~~~~~~~~~~~~~~~~

Delphi tips navigator:
» How to shuffle (randomize positions) array values
« Controling DLL loading

Explore Delphi Programming
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. 2003 Delphi Tips
  7. Grayscaling a bitmap

©2009 About.com, a part of The New York Times Company.

All rights reserved.