delphitimagetstream

Access violation error at delphi while saving/loading image to/from stream


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;

Solution

  • 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;