Search code examples
delphifiremonkeydelphi-10.2-tokyo

How to assign s a FMX.TImage to a VCL.TBitmap?


I try to do this:

BMP.Assign(Image1.Bitmap);

Image1 is a FMX object.
BMP is a standard (VCL.Graphics) bitmap.

The error I get is:

Project Project1.exe raised exception class EConvertError with message
'Cannot assign a TBitmapOfItem to a TBitmap'.

Solution

  • You cannot assign an FMX TBitmap to a VCL TBitmap. They are not compatible with each other (you shouldn't even be mixing VCL and FMX in the same project to begin with, they are not designed to be used together).

    You will have to save the FMX TBitmap to a BMP-formatted stream/file and then load that into the VCL TBitmap.

    Using a file is straight forward:

    Image1.Bitmap.SaveToFile('file.bmp');
    BMP.LoadFromFile('file.bmp');
    

    However, when using a stream instead, FMX's TBitmap.SaveToStream() saves in PNG format only, so you have to use TBitmapCodecManager.SaveToStream() to save in BMP format, eg:

    Strm := TMemoryStream.Create;
    try
      Surface := TBitmapSurface.Create;
      try
        Surface.Assign(Image1.Bitmap);
        TBitmapCodecManager.SaveToStream(Strm, Surface, '.bmp');
      finally
        Surface.Free;
      end;
      Strm.Position := 0;
      BMP.LoadFromStream(Strm);
    finally
      Strm.Free;
    end;