0
votes

I am developing an application in delphi. I am trying to extract an image that is saved in database, save it to TMemoryStream and load same image at TImage control placed on other form that will populate dynamically. I am getting access violation error when I try to load image from stream to image control placed on the form.

Error Description is as follows

Access violation at address 00B548C in module abc.exe. Read of address 0000000

My code snippet is as follows

UniConnection1.Connected := true;  
UniQuery2.SQL.Text := 'Select image from userplays where id = :id';
UniQuery2.Params.ParamByName('id').Value := idpub1;
UniQuery2.Open;
if UniQuery2.FieldByName('image').AsString <> '' then

begin       
   try
   Stream121 := TMemoryStream.Create;
   TBlobField(UniQuery2.FieldByName('image')).SaveToStream(Stream121);
   Stream121.Position := 0;
      if Assigned(Stream121) then
      begin
         Image1.Picture.Graphic.LoadFromStream(Stream121);
         Image1.Update;
      end;

    finally
      Stream121.Free;
    end;
end;
2
Have you checked for Image1.Picture.Graphic <> nil? Do you know what type of image is in the database?Uwe Raabe
jpg image is in the database...actually I am testing it with only database row having image.Vishal Desai
So do some debugging. You've got a nil pointer somewhere you don't expect. Your job is to work out where. If you don't know how to debug this code then your real problem is not this code, but your debugging skills. Fix the debugging skills and this problem will disappear, and every other one like it in the future. In other words, seek to learn skills.David Heffernan

2 Answers

5
votes

TPicture is not able to determine the graphic type in the stream, so you have to tell it before. If you have only JPEG images, you can just hardcode that. Otherwise you should store the image format in the database, too.

var
  graphic: TGraphic;  

Stream121.Position := 0;
if Stream121.size > 0 then begin
  graphic := TJPEGImage.Create;
  try
    graphic.LoadFromStream(Stream121);
    Image1.Picture.Graphic := graphic;
  finally
    graphic.Free;
  end;
end;
2
votes

You are referring to Graphic.LoadfromStream. But Graphic may not (probably will not) exist. You could save to a file and use Picture.LoadFromFile instead (as this will create the appropriate TGraphic descendant) or create Picture.Graphic as the appropriate type (eg TBitmap) first.

Picture.Graphic := TBitMap.Create;

As it stands the image has no idea of what graphic format your data is in. You will need to tell it somehow.