2012-06-13 58 views
3

我的任務是:如何從位圖創建透明PNG圖像?

  1. 創建一個TBitmap對象。
  2. 用透明色填充(alpha = 0)。
  3. 將此位圖分配給TPngImage。
  4. 保存帶alpha透明度的PNG文件。

如何在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; 
+0

只是一個旁註,不要使用'TCanvas.Pixels',它非常緩慢和邪惡;-)使用'TBitmap.Scanline'代替。 – TLama

+1

請參閱[這個答案](http://stackoverflow.com/a/6950006/576719)的問題[如何使用透明度保存png文件?](http://stackoverflow.com/q/6949094/576719)舉一個例子。 –

+0

另一個旁註,你甚至需要一個位圖?你不想直接在PNG圖像畫布上渲染你需要的東西嗎? – TLama

回答

4

或多或少的Dorin's answer的副本。 它顯示瞭如何製作透明png圖像以及如何清除背景。

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;