简体   繁体   中英

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;

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM