为什么我的类函数会失败并出现访问冲突错误?

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

为什么我的类函数

LoadFromFile()
出现访问冲突错误?

Assign()
程序似乎有问题,根据我的调查,访问错误位于以下行:

xquer := Round((P^ + (P + 1)^ + (P + 2)^) / 3);

这是我的代码:

type  /// <summary>
  ///   image processing , convert TBitmap into a FPixels Array of Bytes
  /// </summary>
  TGrayscaleImage = class(TGraphicControl)
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    class function LoadFromFile(const FileName: string) :  TGrayscaleImage ;
    procedure Assign(Source: TPersistent); override;
    procedure SetSize(const x, y: Integer);
    procedure BlackandWhiteImage(Threshold: Byte);
    function ToBitmap: TBitmap;
    property Width: Integer read FWidth write SetWidth;
    property Height: Integer read FHeight write SetHeight;
    property Pixels[x, y: Integer]: Byte read GetPixel write SetPixel;
  end;

class function TGrayscaleImage.LoadFromFile(const FileName: string) :  TGrayscaleImage ;
var
  Bitmap: TBitmap;
  i: Integer;
begin
  result :=  TGrayscaleImage.Create (nil);
  try
    Bitmap := TBitmap.Create;
    try
      Bitmap.LoadFromFile(FileName);
      result.Assign(Bitmap);
    finally
      Bitmap.Free;
    end;
  except
    on E: Exception do
    begin
      result.Free;
      result := nil;
      raise Exception.Create('Error loading file: ' + E.Message);
    end;
  end;
end;
delphi access-violation
1个回答
1
投票

静态方法必须使用类名+方法名来调用;

https://docwiki.embarcadero.com/RADStudio/Sydney/en/Class_Methods

尝试这样:

procedure YourProcedure();
var
   LImage:TGrayscaleImage;
begin
    LImagemage:= TGrayscaleImage.LoadFromFile('image name.ext');
    try
      //work LImage
    finally
      LImagem.Free;
    end;
end;
© www.soinside.com 2019 - 2024. All rights reserved.