Search code examples
delphidelphi-2010

Bitmap with transparency


With code


procedure TForm2.Button1Click(Sender: TObject);
var
  oMeta: TMetaFile;
  oBmp: TBitmap;
begin
  Image1.Transparent := True;
  Image1.Picture.LoadFromFile('D:\data\WMF.wmf');

  oBmp := TBitmap.Create;
  try
    oMeta := TMetaFile(Image1.Picture.Graphic);
    oBmp.SetSize(oMeta.Width, oMeta.Height);
    oBmp.Canvas.Draw(0, 0, oMeta);
    oBmp.SaveToFile('D:\data\WMF.bmp');
  finally
    oBmp.Free;
  end;
end;

I Show wmf image and create bmp file. Created bmp image I show with code


procedure TForm2.Button2Click(Sender: TObject);
begin
  Image1.Transparent := True;
  Image1.Picture.LoadFromFile('D:\data\WMF.bmp');
end;

but image is shown without transparency. Whay ? How can I show this bmp image with transparency ?

TIA and best regards Branko


Solution

  • First of all, you should know that transparent BMP's are very uncommon. Hence, many (most) bitmap viewers, encoders, and decoders do not support transparent bitmaps. However, there is some hope. First of all, many bitmaps are 32-bit, even though the pixels most often are stored in the format $00BBGGRR. The first byte of each "pixel" is hence unused, and one could of course use this as the opacity value: $AABBGGRR. But this is not only my personal ideas. Most bitmaps use the version 3 bitmap header, but version 4 (and version 5) actually supports transparency data. You simply specify the red, green, blue, and alpha masks (e.g. $000000FF, $0000FF00, $00FF0000, and $FF000000, respectively) and then you can store red, green, blue, and alpha intensities per pixel.

    Still, as I said, most bitmap viewers, encoders, and decoders doesn't support transparent bitmaps. I think that the VCL encoders, decoders, and viewer (TImage) don't.

    I would consider using PNG instead of BMP. The PNG bitmap image format supports transparency in a lot of different ways.