Mega Code Archive

 
Categories / Delphi / Forms
 

Transform a TImage.Picture.Bitmap to GrayScale

Title: Transform a TImage.Picture.Bitmap to GrayScale Question: A TBitmap object has no method to convert to GrayScale mode. Answer: However, you can transform a Bitmap to GrayScale with the following procedure: procedure ImageGrayScale(var AnImage: TImage); var JPGImage: TJPEGImage; BMPImage: TBitmap; MemStream: TMemoryStream; begin BMPImage := TBitmap.Create; try BMPImage.Width := AnImage.Picture.Bitmap.Width; BMPImage.Height := AnImage.Picture.Bitmap.Height; JPGImage := TJPEGImage.Create; try JPGImage.Assign(AnImage.Picture.Bitmap); JPGImage.CompressionQuality := 100; JPGImage.Compress; JPGImage.Grayscale := True; BMPImage.Canvas.Draw(0, 0, JPGImage); MemStream := TMemoryStream.Create; try BMPImage.SaveToStream(MemStream); //you need to reset the position of the MemoryStream to 0 MemStream.Position := 0; AnImage.Picture.Bitmap.LoadFromStream(MemStream); AnImage.Refresh; finally MemStream.Free; end; finally JPGImage.Free; end; finally BMPImage.Free; end; end;//fin de ImageGrayScale //MWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM The trick is to assign the content of the Bitmap to a JPEGImage, which has a GrayScale property, and then copy the content of the JPEGImage back to Bitmap, using a MemoryStream. The only drawback is using a JPEGImage, because the JPEGImage has a lousy compression of the image, in other words you loose information with the compression, but the human eye doesnt notice. If you kwnow another implementation please send me an e-mail.