2011. február 2., szerda

Transform a TImage.Picture.Bitmap to GrayScale


A TBitmap object has no method to convert to GrayScale mode.


However, you can transform a Bitmap to GrayScale with the following procedure:

procedure ImageGrayScale(var AnImage: TImage);
  JPGImage: TJPEGImage;
  BMPImage: TBitmap;
  MemStream: TMemoryStream;
  BMPImage := TBitmap.Create;
    BMPImage.Width := AnImage.Picture.Bitmap.Width;
    BMPImage.Height := AnImage.Picture.Bitmap.Height;

    JPGImage := TJPEGImage.Create;
      JPGImage.CompressionQuality := 100;
      JPGImage.Grayscale := True;

      BMPImage.Canvas.Draw(0, 0, JPGImage);

      MemStream := TMemoryStream.Create;
        //you need to reset the position of the MemoryStream to 0
        MemStream.Position := 0;

end; //fin de ImageGrayScale

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 doesn�t notice. If you kwnow another implementation please send me an e-mail.

Nincsenek megjegyzések:

Megjegyzés küldése