加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – 将nil分配给TImage.Picture.Graphic以清除图片后,我该

发布时间:2020-12-15 09:22:39 所属栏目:大数据 来源:网络整理
导读:在下面的代码中,我清除btnSaveClick中的图片,稍后在btnLoadClick中我想为图像分配图片,但它给出了AV,因为Graphic对象不存在. 我怎样才能完成任务? procedure TForm1.btnSaveClick(Sender: TObject);var fs: TFileStream; s: TMemoryStream; buf: TBytes; z:
在下面的代码中,我清除btnSaveClick中的图片,稍后在btnLoadClick中我想为图像分配图片,但它给出了AV,因为Graphic对象不存在.

我怎样才能完成任务?

procedure TForm1.btnSaveClick(Sender: TObject);
var
  fs: TFileStream;
  s:  TMemoryStream;
  buf: TBytes;
  z:  integer;
begin
  fs := TFileStream.Create('c:tempa.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:tempa.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;

解决方法

如果您从具有与注册图像类对应的扩展名的文件加载,您可以简单地执行以下操作:

Picture.LoadFromFile(FileName);

否则,您可以在代码中创建特定TGraphic后代的实例(取决于您正在使用的图形类型)并将其分配给Graphic属性,例如对于JPEG:

var
  Graphic: TJpegImage;
begin
  Graphic := TJpegImage.Create;
  try
    Graphic.LoadFromFile(FileName);
    Picture.Graphic := Graphic;
  finally
    Graphic.Free;
  end;
end;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读