DIB to Tbitmap code manipulation to adapt PNG images?

1.1k views Asked by At

I use this code to convert DIB to TBitmap, so how can i manipulate this code to be suitable to a PNG image (preseving its transparency)? I tired to set the Transparent property to true but it seems that the code was made for 256 color bitmap.

code source: Here

VAR
    BitCount        :  INTEGER;
    BitmapFileHeader:  TBitmapFileHeader;
    BitmapInfo      :  pBitmapInfo;
    DIBinMemory     :  Pointer;
    MemoryStream    :  TMemoryStream;
    NumberOfColors  :  INTEGER;
BEGIN
  RESULT := TBitmap.Create;

  DIBinMemory := GlobalLock(hDIB);
  TRY
    BitmapInfo := DIBInMemory;
    NumberOfColors := BitmapInfo.bmiHeader.biClrUsed;
    BitCount       := BitmapInfo.bmiHeader.biBitCount;
    IF   (NumberOfColors = 0) AND (BitCount <= 8)
    THEN NumberOfColors := 1 SHL BitCount;

    WITH BitmapFileHeader DO
    BEGIN
      bfType := $4D42;  // 'BM'
      bfReserved1 := 0;
      bfReserved2 := 0;
      bfOffBits := SizeOf(TBitmapFileHeader)       +
                   SizeOf(TBitmapInfoHeader)       +
                   NumberOfColors*SizeOf(TRGBQuad);
      bfSize := bfOffBits + BitmapInfo.bmiHeader.biSizeImage;
    END;

    MemoryStream := TMemoryStream.Create;
    TRY
      MemoryStream.Write(BitmapFileHeader, SizeOf(TBitmapFileHeader));
      MemoryStream.Write(DIBInMemory^,
                         BitmapFileHeader.bfSize - SizeOf(TBitmapFileHeader));
      MemoryStream.Position := 0;
      RESULT.LoadFromStream(MemoryStream)
    FINALLY
      MemoryStream.Free
    END

  FINALLY
    GlobalUnlock(hDIB);
    GlobalFree(hDIB)
  END
1

There are 1 answers

2
Uwe Raabe On

You can have a look at PngComponents. The unit PngFunctions.pas contains a method to convert any TGraphic into a png image. As you have tagged your question with TPngImagelist you are probably already using this library anyway.