将nil分配给TImage.Picture.Graphic以清除图片后,如何再次使用它? [英] After assigning nil to TImage.Picture.Graphic to clear the picture, how can I use it again?

查看:102
本文介绍了将nil分配给TImage.Picture.Graphic以清除图片后,如何再次使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我清除了btnSaveClick中的图片,稍后在btnLoadClick中,我想为图片分配图片,但是由于图形对象不存在,它给出了一个AV。

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.

我如何完成任务?

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:

Picture.LoadFromFile(FileName);

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

Otherwise you can create an instance of a specific TGraphic descendant (depending on what type of graphic you're using) in code and assign it to Graphic property, e.g. for JPEG:

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

这篇关于将nil分配给TImage.Picture.Graphic以清除图片后,如何再次使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆