Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a png image into a TImage

Tags:

delphi

I am trying to load a png image into a TImage with Delphi XE4. The png starts off in a stream: E.g.

  Stream := TMemoryStream.Create;
  try
    Stream.LoadFromFile('c:\file.png');
    Stream.Position := 0;
    Image1.Picture.Graphic.LoadFromStream(Stream);
  finally
    Stream.Free;
  end; 

I get an AV when I run this code. Can anyone tell me what I'm doing wrong?

Thanks.

like image 570
RaelB Avatar asked Nov 08 '15 16:11

RaelB


1 Answers

The TImage.Picture.Graphic property is nil until you load a graphic into the Picture.

What you are asking for can be achieved as follows:

  uses pngimage;

  Stream := TMemoryStream.Create;
  try
    // obtain png image, load from file or other..
    ....
    Image := TPngImage.Create;
    try
      Stream.Position := 0;
      Image.LoadFromStream(Stream);
      Image1.Picture.Graphic := Image;
    finally
      Image.Free;
    end;
  finally
    Stream.Free;
  end;
like image 163
RaelB Avatar answered Oct 02 '22 05:10

RaelB