delphi - 比较屏幕截图并获取第一个像素变化的屏幕坐标

标签 delphi

我有两张截图,一张接一张,中间有几秒钟的间隔。我正在比较这两个图像并试图找出它们之间是否有任何差异。如果有任何差异,我需要获取该像素变化的屏幕坐标。

我可以使用 Delphi 实现此目的吗?

最佳答案

如果要比较两个位图并且需要找到第一个不同像素的位置,您可以迭代位图行,获取两个位图每一行的位图像素数组,比较它们,如果不相等匹配,找到不同像素的水平位置。在代码中它可能看起来像这样:

function CompareBitmaps(ABitmap1, ABitmap2: TBitmap;
  var ADiffPixel: TPoint): Boolean;
var
  X, Y: Integer;
  Size: Integer;
  Pixels1, Pixels2: PByteArray;
begin
  // first check if both bitmaps match in size and pixel format
  Result := (ABitmap1.PixelFormat = ABitmap2.PixelFormat) and
    (ABitmap1.Width = ABitmap2.Width) and (ABitmap1.Height = ABitmap2.Height);
  // if so, then...
  if Result then
  begin
    // assign the size of one pixel
    case ABitmap1.PixelFormat of
      pf24bit: Size := SizeOf(TRGBTriple);
      pf32bit: Size := SizeOf(TRGBQuad);
    else
      raise Exception.Create('Bitmap must be 24-bit or 32-bit format!');
    end;
    // iterate all the bitmap rows    
    for Y := 0 to ABitmap1.Height - 1 do
    begin
      // get pointer to pixel data array of the same row for both bitmaps
      Pixels1 := ABitmap1.ScanLine[Y];
      Pixels2 := ABitmap2.ScanLine[Y];
      // compare those pixel data arrays; if they differ, then...
      if not CompareMem(Pixels1, Pixels2, ABitmap1.Width * Size) then
      begin
        // return negative result
        Result := False;
        // assign vertical pixel position to the output ADiffPixel parameter
        ADiffPixel.Y := Y;
        // iterate the current row to find a different pixel; after it's found
        // the pixel's horizontal position is stored to the output ADiffPixel
        // parameter; the pixel array is treated as a byte array, so there's
        // need to be a division by the pixel size
        for X := 0 to ABitmap1.Width * Size - 1 do
          if (Pixels1[X] <> Pixels2[X]) then
          begin
            ADiffPixel.X := X div Size;
            Exit;
          end;
      end;
    end;
  end
  else
    raise Exception.Create('Bitmaps must match in size and pixel format!');
end;

示例用法:

procedure TForm1.Button1Click(Sender: TObject);
var
  PixelPos: TPoint;
begin
  if CompareBitmaps(Image1.Picture.Bitmap, Image2.Picture.Bitmap, PixelPos) then
    ShowMessage('Bitmaps are the same!')
  else
    ShowMessage('Bitmaps are different! The first different pixel was found ' +
      'at [' + IntToStr(PixelPos.X) + '; ' + IntToStr(PixelPos.Y) + '].');
end;

关于delphi - 比较屏幕截图并获取第一个像素变化的屏幕坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15250619/

相关文章:

Delphi XE4 我必须包含什么才能使用函数 FmxHandleToObjC

delphi - 如何获取TVirtualInterface的调用方法参数名称?

delphi - TCameraComponent 和 TVideoCaptureDevice 未在 Win32 中初始化

delphi - 如何扩展内存映射文件的长度?

delphi - 在运行时创建组件 - Delphi

delphi - 在网格上拖动时拖动图像更改

delphi - 将 C stdcall 接口(interface)方法中的变量参数转换为 Delphi

delphi - Delphi:将ShellExecuteEx转换为.txt文件

android - 在 XE5 Delphi 中删除 Android 选项菜单

c# - 如何将位图传递给 Delphi 在 C# 中编写的 dll?