使用 TBmp.Scanline 和 Delphi 逐像素扫描 bmp 文件

问题描述 投票:0回答:1

我正在尝试逐像素扫描 .bmp 文件,以找到每个文件的相关 RGB 值,并将结果分配给 TPanel.Color。

以下是我正在编写的代码

procedure TForm4.FormCreate(Sender: TObject);
begin
  FBmp := TBitmap.Create;
  FBmp.PixelFormat := pf24bit;
  FBmp.LoadFromFile('xxxxx\screen.bmp');
end;

function TForm4.FindPixelColour(const aX, aY: integer): PRGBTriple;
var
  aPixel: PRGBTriple;
begin
  aPixel := FBmp.ScanLine[aY];
  Inc(aPixel, aX);
  Result := aPixel;
end;
procedure TForm4.UpdatePanel(const aPixel: PRGBTriple);
var
  Conversion: integer;
begin
  PnlColour.Color := RGB(aPixel.rgbtRed, aPixel.rgbtGreen, aPixel.rgbtBlue);
  Conversion := aPixel.rgbtRed;
  label1.Caption := 'Red: ' + IntToStr(Conversion);
  Conversion := aPixel.rgbtGreen;
  label2.Caption := 'Green: ' + IntToStr(Conversion);
  Conversion := aPixel.rgbtBlue;
  label3.Caption := 'Blue: ' + IntToStr(Conversion);
end;

procedure TForm4.FormDestroy(Sender: TObject);
begin
  fbmp.Free;
end;

程序执行时,FindPixelColour 的结果似乎不一致。有时 RGB 转换会在 PnlColour.Color 中显示正确的颜色,但其他转换则不会。

我确定 .bmp 文件是 24 位的,但我也尝试将其更改为 36 位并相应地修改

FBmp.PixelFormat
但仍然不高兴。

我哪里做错了?这是我扫描 .bmp 的方式还是我将

TForm4.FindPixelColour
检索到的颜色分配给
PnlColour.Color
的方式?

delphi-xe2
1个回答
0
投票

我从这个答案

中找到了解决方案

这是经过改进的正确代码

procedure TForm4.FormCreate(Sender: TObject);
begin
  FBmp := TBitmap.Create;
  img.Picture.LoadFromFile('xxxx\screen.bmp');
  FBmp.LoadFromFile('xxxx\screen.bmp');
  case FBmp.PixelFormat of
    pf24bit:
      FSize := SizeOf(TRGBTriple);
    pf32bit:
      FSize := SizeOf(TRGBQuad);
  else
    // if the image is not 24-bit or 32-bit go away
    begin
      ShowMessage('Your bitmap has unsupported color depth!');
      Exit;
    end;
  end;
end;
function TForm4.FindPixelColour(const aX, aY: integer): PByteArray;
var
  aPixel: PByteArray;
begin
  aPixel := FBmp.ScanLine[aY];
  Result := aPixel;
end;
procedure TForm4.UpdatePanel(aPixel: PByteArray; const aX: Integer);
var
  Red, Green, Blue: byte;
begin
  Red := aPixel^[(aX * FSize) + 2]; //Red
  label1.Caption := 'Red: ' + IntToStr(Red);

  Green := aPixel^[(aX * FSize) + 1]; //Green
  label2.Caption := 'Green: ' + IntToStr(Green);

  Blue := aPixel^[(aX * FSize)];
  label3.Caption := 'Blue: ' + IntToStr(Blue);
  PnlColour.Color := RGB(Red, Green, Blue);
end;

主要更改是从

Inc(aPixel, aX);
中删除
TForm4.FindPixelColour
以及在
TForm4.UpdatePanel

中查找颜色通道的不同方式
© www.soinside.com 2019 - 2024. All rights reserved.