Mega Code Archive

 
Categories / Delphi / Graphic
 

How to convert a color graphic into gray scale

Title: How to convert a color graphic into gray scale Question: How to convert a color graphic into gray scale Answer: procedure TForm1.Button1Click(Sender: TObject); var lo:tbitmap; i,j:integer; kl:longint; rr,gg,bb:byte; res:byte; begin lo:=tbitmap.create; lo.Width:=image1.Width; lo.height:=image1.height; ProgressBar1.Max:=image1.Width+1; for i:=0 to image1.Width+1 do begin for j:=0 to image1.height+1 do begin kl:=ColorToRGB(image1.Canvas.Pixels[i,j]); rr:=byte(kl); gg:=byte(kl shr 8); bb:=byte(kl shr 8); res:=(rr+gg+bb) div 3; lo.Canvas.Pixels[i,j]:=rgb(res,res,res); end; ProgressBar1.Position:=i; end;//for do image1.Canvas.Draw(0,0,lo); lo.free; end; the principle on which the code work is actually very simple what is happening is that when you evaluete a color variable you will see that it consists of 4 parts. red green blue and windows pallete info this is split up like this FF FF FF FF Palletteinfo blue green red when the blue,green and red values are added together and are devided by 3 you will always get a grey value. This procedure works by moving the value we want to right and then typecasting it to a byte. When we typcast something the we start with the least significant bit and work our way up until it is equal in size to the variable we are typecasting it. if we look at a binary representation it looks like this 1111 1111 1111 1111 1111 1111 1111 1111 this is white 1111 1111 1111 1111 0000 0000 0000 0000 this is blue {byte } when a value like the above is shr the following happens it changes to: 0000 0000 1111 1111 1111 1111 0000 0000 this is now yellow this code is not very fast and can definitly be improved what could be used is the scanline procedure of tbitmap which would probably speed up things. if you only want to split the rgb channels instead of counting the 3 rgb values together use each seperately to draw each channel.