Using PNG images for buttons in Lazarus/FPC from resource script .RC or compiled resource file .RES

Some components already has a method LoadFromResource to load picture from resource, but it works only with bitmap resources. And calling it for png images will rise an “EResNotFound” exception.

So here is my solution.
First create a resource script file with .RC extention:

ADD_PNG    RCDATA "images\\add.png";
EDIT_PNG   RCDATA "images\\edit.png";
REMOVE_PNG RCDATA "images\\remove.png";

Then add this file to the unit with an option {$R}


implementation

{$R filename.rc}

Create a procedure to simplify calling :

procedure PngImageFromResources(APicture: TPicture; AResourceName: string);
var
  png: TPNGImage;
  rs: TResourceStream;
begin
  png := TPNGImage.Create;
  rs := TResourceStream.Create(HInstance, AResourceName, RT_RCDATA);
  try
    png.LoadFromStream(S, S.Size);
    APicture.Graphic.Assign(png);
  finally
    png.Free;
    s.Free;
  end; 
end;

And to finish call a procedure with a TPicture object and resource name as parameters:


 PngImageFromResources(BitBtn1.Glyph.Picture, 'ADD_PNG');

Leave a Reply

Your email address will not be published. Required fields are marked *