delphijpegaccess-violationassigntimage

Why do I get an access violation when assigning a JPEG to an array of TJPEGImages?


  Formulae: array [1..6] of TJPEGImage;

I have an array in which I want to assign images into so that I can display them onto a form. I've used similar code from the JPEG data-stream to TImage question but I get an access violation error message at the if statement

procedure Tfrm_calc2.ChangeDisplay(ImgNo: Integer; NewImage: Boolean);
var
  TempImg: TJPEGImage;
begin
  TempImg:= TJPEGImage.Create;
  TempImg.LoadFromFile('C2F'+inttostr(ImgNo)+'.jpg');
  img_Formulae.Picture.Assign(TempImg);

 // assigning each picture to an element in array if it is the first time. This will be used to save the pictures later on
  If NewImage = True then Formulae[ImgNo].Assign(TempImg);


  TempImg.Free;
  ImgDisplayed:= ImgNo;

  lbl_FormulaDisplay.Caption:= 'Formula ' + inttostr(ImgNo); //user can see which formula can be seen
end;

Thanks.


Solution

  • Did you populate the array with allocated objects before calling Assign on them? Probably not. Try something more like this instead:

    procedure Tfrm_calc2.ChangeDisplay(ImgNo: Integer);
    var
      TempImg: TJPEGImage;
    begin
      TempImg := TJPEGImage.Create;
      try
        TempImg.LoadFromFile('C2F'+IntToStr(ImgNo)+'.jpg');
        img_Formulae.Picture.Assign(TempImg);
    
        if Formulae[ImgNo] = nil then
        begin
          Formulae[ImgNo] := TempImg;
          TempImg := nil;
        end else
          Formulae[ImgNo].Assign(TempImg);
      finally
        TempImg.Free;
      end;
      ImgDisplayed := ImgNo;
      lbl_FormulaDisplay.Caption := 'Formula ' + IntToStr(ImgNo);
    end;
    

    Alternatively:

    procedure Tfrm_calc2.ChangeDisplay(ImgNo: Integer);
    var
      TempImg: TJPEGImage;
    begin
      TempImg := TJPEGImage.Create;
      try
        TempImg.LoadFromFile('C2F'+IntToStr(ImgNo)+'.jpg');
        img_Formulae.Picture.Assign(TempImg);
    
        FreeAndNil(Formulae[ImgNo]);
        Formulae[ImgNo] := TempImg;
      except
        TempImg.Free;
        raise;
      end;
      ImgDisplayed := ImgNo;
      lbl_FormulaDisplay.Caption := 'Formula ' + IntToStr(ImgNo);
    end;