如何通过ScanLine复制灰度位图

问题描述

我想将像素从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;

对于保存的图像,图形编辑器显示“像素深度/颜色:索引的256个调色板”。

解决方法

可能值得指出的是,一个8位的位图不一定是灰度的。

Instead,它是带有“颜色表”的位图,其中“颜色表”最多包含256个条目,每个像素都引用此表中的一个条目。因此,如果像素的值为185,则意味着它应使用位图“颜色表”中位置185处的颜色。因此,一个8位的位图与一个16位,24位或32位的位图相比完全不同,后者没有颜色表,而是在每个像素处具有实际的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;

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...