Loading images into TImage, via array

Danny Robinson picture Danny Robinson · Sep 30, 2011 · Viewed 8.5k times · Source

I'm very new to delphi, doing a project for my A level. When I run my code the images just don't show, I've looked everywhere and my teacher can't help me. Can anyone tell me what I'm missing?

    const
       Animal : array[0..6] of string =                    ('Bears','Dogs','Cats','Chickens','Horses','Cows','Monkeys');
    ImagePaths : array [0..6] of string
      = ('img0.JPG', 'img1.JPG', 'img2.JPG', 'img3.JPG', 'img4.JPG', 'img5.JPG',
        'img6.JPG');

  var i:integer;
  Images : array [0..11] of TImage;

procedure LoadImages;
  var
  k,l:integer;
  begin
  Randomize;
  k:=Random(11);
  for l:= 0 to k do
  begin
    Images[l] := TImage.Create(nil);
    Images[l].Picture.LoadFromFile(ImagePaths[i])
  end

end;

procedure TForm4.FormCreate(Sender: TObject);
begin
randomize;
i:=random(6);
QuestionLbl.Caption:=Format('How many %s are there?',[Animal[i]]);
LoadImages;
end;

The idea is that a random number of images of the same randomly selected animal is displayed for a child to then count and input, if that helps. Much appreciate any help.

edit.

as this is only a prototype I have copied it all to a new application and this is all the code I didn't include:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics,     Controls, Forms,
  Dialogs, StdCtrls,jpeg, ExtCtrls;

type
  TForm1 = class(TForm)
    QuestionLbl: TLabel;
    procedure FormCreate(Sender: TObject);
      private
    { Private declarations }
  public
    { Public declarations }
  end;

The same error is occurring and I'm afraid I'm too ignorant to follow what I'm sure were very clear instructions.

Answer

David Heffernan picture David Heffernan · Sep 30, 2011

What appears to be missing is that you need to tell the image which control is its parent so that it can appear on screen. Do that like this:

Images[l].Parent := TheForm;

Obviously your form variable will have a different name, but I'm sure you know what it's called.

When you do this you will find that they all end up on top of each other. Assign to the Top and Left properties to position then. Finally you will likely want to set the Height and Width properties of the images to match the dimensions of the images, Images[l].Picture.Height and Images[l].Picture.Width.


I can't imagine why your code produces an access violation but it's presumably unrelated to the question you asked. The following code proves that what I say above is correct:

procedure TMyForm.FormCreate(Sender: TObject);
var
  Image: TImage;
begin
  Image := TImage.Create(Self);
  Image.Parent := Self;
  Image.Picture.LoadFromFile('C:\desktop\image.jpg');
  Image.Top := 0;
  Image.Left := 0;
  Image.Height := Image.Picture.Height;
  Image.Width := Image.Picture.Width;
end;

Without your full code I cannot debug your AV.