贴一段相似代码
function GetImageMask(Image: TBitmap;
ColorValid: boolean;
AColor: TColor): TBitmap;
var
TransparentColor: TColor;
cColor: TColorRef;
bmAndObject, bmObjectOld: HBitmap;
hdcObject, hdcTemp, DC: HDC;
ptSize: TPoint;
Pal: HPalette;
begin
DC := GetDC(0);
if ColorValid then
TransparentColor := AColor {color has already been selected}
else
{set the transparent color to be the lower left pixel of the bitmap}
TransparentColor := Image.Canvas.Pixels[0, Image.Height - 1];
TransparentColor := TransparentColor or $02000000;
hdcTemp := CreateCompatibleDC(DC);
SelectObject(hdcTemp, Image.Handle);
{ select the bitmap }
{ convert bitmap dimensions from device to logical points}
ptSize.x := Image.Width;
ptSize.y := Image.Height;
DPtoLP(hdcTemp, ptSize, 1);
{ convert from device logical points }
{ create some DCs to hold temporary data}
hdcObject := CreateCompatibleDC(DC);
{ create a bitmap for each DC}
{ monochrome DC}
bmAndObject := CreateBitmap(ptSize.x, ptSize.y, 1, 1, nil);
{ each DC must select a bitmap object to store pixel data}
bmObjectOld := SelectObject(hdcObject, bmAndObject);
{ set proper mapping mode}
SetMapMode(hdcTemp, GetMapMode(DC));
{ set the background color of the source DC to the color.
contained in the parts of the bitmap that should be transparent}
Pal := Image.Palette;
SelectPalette(hdcTemp, Pal, False);
RealizePalette(hdcTemp);
cColor := SetBkColor(hdcTemp, TransparentColor);
{ create the object mask for the bitmap by performing a BitBlt()
from the source bitmap to a monochrome bitmap}
BitBlt(hdcObject, 0, 0, ptSize.x, ptSize.y, hdcTemp, 0, 0, SRCCOPY);
{ set the background color of the source DC back to the original color}
SetBkColor(hdcTemp, cColor);
{Save the Object bitmap}
try
Result := TBitmap.Create;
try
Result.Handle := bmAndObject;
except
Result.Free;
raise;
end;
except
Result := nil;
end;
{ delete the memory bitmaps}
SelectObject(hdcObject, bmObjectOld);
{ delete the memory DCs}
DeleteDC(hdcObject);
DeleteDC(hdcTemp);
ReleaseDC(0, DC);
end;