Javid
Javid

Reputation: 2935

TPNGImage `LoadFromStream` is not working in some cases

I'm using VCL TPNGImage class to load PNG images. If I create the TPNGImage object using FindClass(S).Create(S is a String and it might contain 'TPNGImage'), when I try to load the png image using LoadFromStream I fade an access violation exception. Do you have any ideas?

Note that I use the following code to create a new instance:

P := TPNGImage(FindClass('tpngimage').NewInstance);

Upvotes: 2

Views: 1162

Answers (1)

David Heffernan
David Heffernan

Reputation: 612964

You say that you create the class by calling:

P := TPNGImage(FindClass('tpngimage').NewInstance);

That code will allocate an instance, but will not run the constructor. And that is your problem. You cannot expect an instance to work if you have not constructed it properly.

You need to use

P := TPNGImage.Create;

Now, it sounds as though you want to be able to write code that can work on a variety of TGraphic descendent. You can make that work.

First of all declare your variable to be of type TGraphic.

var
  Image: TGraphic;

And then get hold of a class reference.

var
  Cls: TPersistentClass;
....
Cls := FindClass('TPNGImage');

And then instantiate the object, if the class reference is compatible.

if Cls.InheritsFrom(TGraphic) then
  Image := TGraphicClass(Cls).Create;

Because TGraphic uses a virtual constructor that will run the TPNGImage constructor. You could use this same code to construct JPEG, BMP, GIF etc.

Upvotes: 6

Related Questions