我从网上查到了下面的程序,问题解决了,最后成功保存为256级灰度(不是256色)图形了:
function GammaConv(Value: double; Gamma: double): double;
begin
if Value <> 0 then Result := Exp(Ln(Value)/Gamma) else Result := 0;
end;
function CreateGrayPalette(Num: integer; Gamma: double): HPalette;
var
lPal: PLogPalette;
i: integer;
begin
// Add the Grayscale palette
lPal :=AllocMem(sizeof(TLogPalette) + Num * sizeof(TPaletteEntry));
lPal.palVersion := $300;
lPal.palNumEntries := Num;
for i := 0 to Num-1 do
with lPal.palPalEntry do
begin
peRed:=Round(255*GammaConv(i/(Num-1),Gamma));
peGreen:=Round(255*GammaConv(i/(Num-1),Gamma));
peBlue:=Round(255*GammaConv(i/(Num-1),Gamma));
peFlags:=0;
end;
Result:=CreatePalette(lPal^);
FreeMem(lPal);
Win32Check(longbool(Result));
end;
procedure ConvertToGray_256(bmp: TBitmap);
var
gm : TBitmap; // Destination grayscale bitmap
x, y : integer;
p1 : PRGBArray;
p2 : PByteArray;
begin
bmp.PixelFormat := pf24bit;
gm := TBitmap.Create;
gm.PixelFormat:=pf8bit; gm.Width:=bmp.Width; gm.Height:=bmp.Height;
gm.Palette := CreateGrayPalette(256, 1.4);
for y := 0 to bmp.Height-1 do
begin
p1 := bmp.ScanLine[y];
p2 := gm.ScanLine[y];
for x:=0 to bmp.Width-1 do with p1^[x] do p2^[x]:=(Red*3+Grn*4+Blu) div 8; //得到灰度值
end;
bmp.Assign(gm);
gm.Free;
end;
多谢各位!