Reputation: 233
i want to load images from URL list in ListBox items, this my code to retrieve the URLs
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;
UPDATE 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;
i tried loading the pictures in another ListBox, however, there are items added but without pictures !
Upvotes: 2
Views: 1301
Reputation: 597176
After TIdHTTP.Get()
downloads the image to your TMemoryStream
, you need to seek the stream to Position 0 before you do anything with it, like loading it into your Bitmap
. And add a try..except
block to handle download errors.
Also, you should be using a second try..finally
block for freeing the 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;
Upvotes: 1