2

我想从 ListBox 项目中的 URL 列表中加载图像,这是我检索 URL 的代码

var
 LJSONArray : TJSONArray;
 LEntity: TBackendEntityValue;
 I : integer;
begin
 try
  LJSONArray := TJSONArray.Create;
  BackendStorage1.Storage.QueryObjects('list', [], LJSONArray);
   for I := 0 to LJSONArray.Count-1 do
    begin
     ListBox4.Items.Add (LJSonArray.Items[I].GetValue<string>('Pictures'));
    end;
  finally
  LJSONArray.Free;
 end;
 end;

更新 1

procedure TForm1.Button1Click(Sender: TObject);
var
 LBItem    : TListBoxItem;
 i: integer;
 HTTP : TIdHttp;
 Stream : TMemoryStream;
begin
 HTTP := TIdHttp.Create(nil);
try
 for i := 0 to ListBox1.Items.Count-1 do
  begin
   LBItem := TListBoxItem.Create(nil);
   LBItem.Parent := ListBox2;
   LBItem.Height := 100;
   Stream := TMemoryStream.Create;
   HTTP.Get(ListBox1.Items.Strings[i], Stream);
   LBItem.ItemData.Bitmap.LoadFromStream(Stream);

  end;
 finally
  Stream.Free;
  HTTP.Free;
end;
end;

我尝试将图片加载到另一个列表框中,但是,添加了一些项目但没有图片!

4

1 回答 1

1

TIdHTTP.Get()图像下载TMemoryStream到您的Bitmap. 并添加一个try..except块来处理下载错误。

此外,您应该使用第二个try..finally块来释放TMemoryStream.

procedure TForm1.Button1Click(Sender: TObject);
var
 LBItem    : TListBoxItem;
 i: integer;
 HTTP : TIdHttp;
 Stream : TMemoryStream;
begin
 HTTP := TIdHttp.Create(nil);
try
 for i := 0 to ListBox1.Items.Count-1 do
  begin
   LBItem := TListBoxItem.Create(nil);
   LBItem.Parent := ListBox2;
   LBItem.Height := 100;
   Stream := TMemoryStream.Create;
   try
     try
       HTTP.Get(ListBox1.Items.Strings[i], Stream);
       Stream.Position := 0; // <-- add this
       LBItem.ItemData.Bitmap.LoadFromStream(Stream);
     except
       // do something else
     end;
   finally
     Stream.Free;
   end;
  end;
 finally
  HTTP.Free;
 end;
end;
于 2016-05-29T17:12:29.673 回答