WeG*_*ars 2 delphi bitmap tbitmap
我想将像素从 BMP1 复制到 BMP2 但复制的图像是乱码。为什么?
注:输入图像为pf8bit;
TYPE
TPixArray = array[0..4095] of Byte;
PPixArray = ^TPixArray;
procedure Tfrm1.CopyImage;
VAR
BMP1, BMP2: TBitmap;
y, x: Integer;
LineI, LineO: PPixArray;
begin
BMP1:= TBitmap.Create;
BMP2:= TBitmap.Create;
TRY
BMP1.LoadFromFile('test.bmp');
BMP2.SetSize(BMP1.Width, BMP1.Height);
BMP2.PixelFormat:= BMP1.PixelFormat;
for y:= 0 to BMP1.Height -1 DO
begin
LineI := BMP1.ScanLine[y];
LineO := BMP2.ScanLine[y];
for x := 0 to BMP1.Width -1 DO
LineO[x]:= LineI[x];
end;
//BMP2.SaveToFile('out.bmp');
imgOut.Picture.Assign(BMP2); //TImage
FINALLY
FreeAndNil(BMP2);
FreeAndNil(BMP1);
END;
end;
Run Code Online (Sandbox Code Playgroud)
对于保存的图像,图形编辑器会显示“像素深度/颜色:索引,256 色板”。
值得指出的是,8 位位图不一定是灰度的。
相反,它是一个带有“颜色表”的位图,最多包含 256 个条目,每个像素都引用此表中的一个条目。因此,如果一个像素的值为 185,这意味着它应该使用位图“颜色表”中位置 185 处的颜色。因此,与 16 位、24 位或 32 位位图相比,8 位位图的工作方式完全不同,后者没有颜色表,但每个像素都有实际的 RGB(A) 值。
您的情况的问题可能是目标像素图与源位图的颜色表不同。
实际上,我以前从未使用过 8 位位图和调色板,但我认为这很简单:
var
s, t: TBitmap;
y: Integer;
sp, tp: PByte;
x: Integer;
begin
s := TBitmap.Create;
try
s.LoadFromFile('C:\Users\Andreas Rejbrand\Desktop\bitmap.bmp');
Assert(s.PixelFormat = pf8bit);
t := TBitmap.Create;
try
t.PixelFormat := pf8bit;
t.SetSize(s.Width, s.Height);
t.Palette := s.Palette; // <-- Let the new image have the same colour table
for y := 0 to s.Height - 1 do
begin
sp := s.ScanLine[y];
tp := t.ScanLine[y];
for x := 0 to s.Width - 1 do
tp[x] := sp[x];
end;
t.SaveToFile('C:\Users\Andreas Rejbrand\Desktop\bitmap2.bmp');
finally
t.Free;
end;
finally
s.Free;
end;
Run Code Online (Sandbox Code Playgroud)