5

My task is:

  1. Create a TBitmap object.
  2. Fill it with transparent color (alpha = 0).
  3. Assign this bitmap to TPngImage.
  4. Save PNG file with alpha transparency.

How can I do it in Delphi XE?

var
  Png: TPngImage;
  X, Y: Integer;
  Bitmap: TBitmap;
begin
  Bitmap := TBitmap.Create();
  Bitmap.PixelFormat := pf32bit;
  Png := TPngImage.Create();
  try
    Bitmap.SetSize(100, 100);

    // How to clear background in transparent color correctly?
    // I tried to use this, but the image in PNG file has solid white background:
    for Y := 0 to Bitmap.Height - 1 do
      for X := 0 to Bitmap.Width - 1 do
        Bitmap.Canvas.Pixels[X, Y]:= $00FFFFFF;

    // Now drawing something on a Bitmap.Canvas...
    Bitmap.Canvas.Pen.Color := clRed;
    Bitmap.Canvas.Rectangle(20, 20, 60, 60);

    // Is this correct?
    Png.Assign(Bitmap);
    Png.SaveToFile('image.png');
  finally
    Png.Free();
    Bitmap.Free();
  end;
end;
Andrew
  • 3,696
  • 3
  • 40
  • 71
  • Just one sidenote, don't use `TCanvas.Pixels`, it's terribly slow and evil ;-) Use `TBitmap.Scanline` instead. – TLama Jun 13 '12 at 10:20
  • 1
    See [this answer](http://stackoverflow.com/a/6950006/576719) to the question [How to save a png file with transparency?](http://stackoverflow.com/q/6949094/576719) for an example. – LU RD Jun 13 '12 at 10:50
  • Another sidenote, do you even need a bitmap ? Don't you want to render what you need directly on a PNG image canvas ? – TLama Jun 13 '12 at 10:57
  • @LURD Thanks, now I understand how to fill with transparent color: by settings `Bitmap.TransparentColor` and `Bitmap.Transparent` after filling background. Can you add this as answer please? – Andrew Jun 13 '12 at 10:58
  • @TLama When I tried to do that, I got error "Canvas does not allow drawing" – Andrew Jun 13 '12 at 10:59
  • 2
    @Andrew, you need to instantiate the `TPNGImage` by using `CreateBlank` not by `Create` to make its canvas drawable. – TLama Jun 13 '12 at 20:32
  • @TLama Great, didn't even know about this constructor. – Andrew Jun 13 '12 at 20:40

1 Answers1

5

More or less a copy of Dorin's answer. It shows how to make a transparent png image and how to clear the background.

uses
  PngImage;
...

var
  bmp: TBitmap;
  png: TPngImage;
begin
  bmp := TBitmap.Create;
  bmp.SetSize(200,200);

  bmp.Canvas.Brush.Color := clBlack;
  bmp.Canvas.Rectangle( 20, 20, 160, 160 );

  bmp.Canvas.Brush.Style := bsClear;
  bmp.Canvas.Rectangle(1, 1, 199, 199);

  bmp.Canvas.Brush.Color := clWhite;
  bmp.Canvas.Pen.Color := clRed;
  bmp.Canvas.TextOut( 35, 20, 'Hello transparent world');

  bmp.TransparentColor := clWhite;
  bmp.Transparent := True;

  png := TPngImage.Create;
  png.Assign( bmp );
  png.SaveToFile( 'C:\test.png' );

  bmp.Free;
  png.Free;
end;
Community
  • 1
  • 1
LU RD
  • 34,438
  • 5
  • 88
  • 296