如何正确实现TBitmap的扫描线访问?

时间:2012-05-01 16:26:46

标签: delphi graphics bitmap delphi-xe2 scanline

我正在尝试根据article on Embarcadero访问位图的扫描线。使用扫描线,如

for y := 0 to n do
begin
   line := bitmap.scanline [y];
   for x := 0 to n do line [x] := value;

我之前已经实施过。我注意到访问扫描线需要相当多的时间,上面提到的文章提供了解决方案。我无法正确实现它。我的代码是:

unit SCTester;

interface

uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
     ExtCtrls;

type
   TRGBQuad = packed record
      b: uInt8;
      g: uInt8;
      r: uInt8;
      alpha: uInt8;
   end; // Record: TQuad //

// Override the definitions in Graphics.pas
   TRGBQuadArray = packed array [0..MaxInt div SizeOf (TRGBQuad) - 1] of TRGBQuad;
   PRGBQuadArray = ^TRGBQuadArray;

  TForm1 = class(TForm)
    Image: TImage;
    procedure ImageDblClick(Sender: TObject);
  end;

var Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.ImageDblClick(Sender: TObject);
var Bitmap: TBitmap;
    q: TRGBQuad;
    x, y: NativeInt;
    FirstLine: PRGBQuadArray;
    idx: NativeInt;
    LineLength: NativeInt;
begin
   q.r := 0; q.g := 0;
   Bitmap := TBitmap.Create;
   Bitmap.Height := Image.Height;
   Bitmap.Width  := Image.Width;
   Bitmap.PixelFormat := pf32Bit;
   FirstLine := Bitmap.ScanLine [0];
   LineLength := (NativeInt (Bitmap.Scanline [1]) - NativeInt (FirstLine)) div SizeOf (TRGBQuad);
   try
      for y := Bitmap.Height - 1 downto 0 do
      begin
         for x := 0 to Bitmap.Width - 1 do
         begin
            q.b := (x xor y) mod 255;
            idx := y * LineLength + x;
            FirstLine [idx] := q;
         end; // for
      end; // for
      Image.Picture.Assign (Bitmap);
   finally
       Bitmap.Free;
   end; // try..finally
end;

end.

当y = 1且x = 0时,我总是被非法访问。 LineLength是负数(位图的宽度),但可能是预期的。我做错了什么?

编辑:上述代码已更改,以反映到目前为止处理的评论。

2 个答案:

答案 0 :(得分:5)

为了不访问任何负面索引,我会这样做

procedure TForm1.Button1Click(Sender: TObject);
var Bitmap: TBitmap;
    q: TRGBQuad;
    x, y: LongInt;
    line{, FirstLine}: PRGBQuadArray;
    idx: NativeInt;
    LastLine: PRGBQuadArray;
    LineLength: NativeInt;
begin
   q.r := 0; q.g := 0;
   Bitmap := TBitmap.Create;
   Bitmap.Height := Image.Height;
   Bitmap.Width  := Image.Width;
   Bitmap.PixelFormat := pf32Bit;

   LastLine := Bitmap.ScanLine[Bitmap.Height - 1];
   LineLength := (NativeInt(Bitmap.Scanline[Bitmap.Height - 2]) - NativeInt(Lastline)) div SizeOf(TRGBQuad);
   try
      for y := 0 to Bitmap.Height - 1 do
      begin
         for x := 0 to Bitmap.Width - 1 do
         begin
            q.b := (x xor y) mod 255;
            idx := y * LineLength + x;
            LastLine [idx] := q;
         end; // for
      end; // for
      Image.Picture.Assign (Bitmap);
   finally
       Bitmap.Free;
   end; // try..finally
end;

答案 1 :(得分:1)

LineLength对很多位图都是负数,因为它们经常使用自下而上的方法来存储行。 MSDN: BITMAPINFOHEADER。因此,应该针对这种情况修改此解决方案。