DIB转TBitmap代码处理以适应PNG图片?

3
我使用这段代码将DIB转换为TBitmap,那么我该如何修改此代码以适用于PNG图像(保留其透明度)?我尝试将Transparent属性设置为true,但似乎该代码是为256色位图而设计的。
代码来源:这里
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个回答

1

您可以查看PngComponents。单元PngFunctions.pas包含一种将任何TGraphic转换为PNG图像的方法。由于您已经使用了TPngImagelist标签,因此您可能已经在使用此库。


谢谢Uwe,但问题是当我从上面的代码获取位图时,它会失真(没有透明度)。 - Sara S.
问题在于我使用一个SDK旋转PNG图像,该SDK输出DIB句柄作为图像,但当我保存并重新打开它时,它可以正常工作。从DIB到位图的转换会扭曲透明度。 - Sara S.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接