In the code below, I clear the Picture in btnSaveClick, later in btnLoadClick I want to assign a picture to the image, but it gives an AV because the Graphic object does not exist.
How can I accomplish the task?
procedure TForm1.btnSaveClick(Sender: TObject);
var
fs: TFileStream;
s: TMemoryStream;
buf: TBytes;
z: integer;
begin
fs := TFileStream.Create('c:\temp\a.my', fmCreate);
s := TMemoryStream.Create;
try
Image1.Picture.Graphic.SaveToStream(s);
z := s.Size;
SetLength(buf, z);
s.Position := 0;
s.ReadBuffer(buf[0], z);
fs.WriteBuffer(z, SizeOf(integer));
fs.WriteBuffer(buf[0], z);
finally
s.Free;
fs.Free;
end;
ShowMessage('ok');
Image1.Picture.Graphic := nil;
end;
procedure TForm1.btnLoadClick(Sender: TObject);
var
fs: TFileStream;
s: TMemoryStream;
buf: TBytes;
z: integer;
gc: TGraphicClass;
begin
fs := TFileStream.Create('c:\temp\a.my', fmOpenRead);
s := TMemoryStream.Create;
try
fs.ReadBuffer(z, SizeOf(integer));
SetLength(buf, z);
fs.ReadBuffer(buf[0], z);
s.WriteBuffer(buf[0], z);
s.Position := 0;
Image1.Picture.RegisterFileFormat('jpg', 'jpeg files', gc);
// Image1.Picture.Graphic.LoadFromStream(s); <-- AV here. Whats the proper way to do it?
finally
s.Free;
fs.Free;
end;
ShowMessage('ok');
end;
If you’re loading from a file with an extension which corresponds with a registered image class you can simply do:
Otherwise you can create an instance of a specific
TGraphicdescendant (depending on what type of graphic you’re using) in code and assign it toGraphicproperty, e.g. for JPEG: