Grayscaling A Bitmap

Submitted by:Jhon Jhon

Date added:02 April, 2012

Category:Delphi

Delphi code example for Grayscaling A Bitmap

Tags: bitmap

Code Snippet:

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;
 
 

Comments