How to insert picture in the Delphi program itself?
Asked Answered
W

2

6

I have used a TImage component in my program.

At runtime, I add an image to the component by using:

Image1.Picture.LoadFromFile('C:\Users\53941\Pictures\eq1.jpg');

Now, I want to run this program on some other computer, which would not have this image file at the source I have given in the code.

So, how can I store this image file in the program executable itself?

Waring answered 25/7, 2017 at 17:7 Comment(0)
I
12

Store the image file in the program's resources, using an .rc script or the IDE's Resources and Images dialog. Read Embarcadero's documentation for more details:

Resources and Images

You can then use a TResourceStream to access the resource data at runtime. Construct a TJPEGImage object, load the stream into it, and assign it to the TImage:

uses
  ..., Classes, Jpeg;

var
  Strm: TResourceStream;
  Jpg: TJPEGImage;
begin 
  Strm := TResourceStream.Create(HInstance, '<Resource identifier>', RT_RCDATA);
  try
    Jpg := TJPEGImage.Create;
    try
      Jpg.LoadFromStream(Strm);
      Image1.Picture.Assign(Jpg);
    finally
      Jpg.Free;
    end;
  finally
    Strm.Free;
  end;
end;
Infinity answered 25/7, 2017 at 17:20 Comment(0)
P
7

You can assign the image using the Object Inspector when designing the Form. The image will be stored in the Form's DFM and be loaded automatically when the program runs.

Select the TImage and, in the Object Inspector,

  • select the Picture property
  • click the ... button to open the Picture Editor
  • press the Load... button and select the image file
  • Close the editor with the OK button.

If you want to load the image in code instead, simply do as Remy showed.

Pennon answered 25/7, 2017 at 17:22 Comment(5)
Using a resource is better because you can keep the asset directly in your revision control system. Pushing it into the .dfm file makes traceability harder.Edict
Sure, but that is the usual, RAD way.Pennon
Yes. And it sucks. Speaking as a software developer.Edict
It depends on your needs. For simple programs, or mockups, or simply for starters, it makes a lot of sense. If the program then gets larger, you can always refactor.Pennon
Worth mentioning that the dfm will store a bitmap. Might be unadvisable for large images.Instrumentality

© 2022 - 2024 — McMap. All rights reserved.