如何将图像从URL添加到ListBox

时间:2016-05-28 19:17:43

标签: android delphi firemonkey delphi-10.1-berlin

我想从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;

我尝试在另一个ListBox中加载图片,但是,有些项目已添加但没有图片!

1 个答案:

答案 0 :(得分:0)

TMemoryStream将图片下载到Bitmap后,您需要在对其执行任何操作之前先找到位置0的流,例如将其加载到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;

$_POST