【问题标题】:how to add images from URL to ListBox如何将图像从 URL 添加到 ListBox
【发布时间】:2016-05-28 19:17:43
【问题描述】:

我想从 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 中,但是,添加了一些项目但没有图片!

【问题讨论】:

    标签: android delphi firemonkey delphi-10.1-berlin


    【解决方案1】:

    TIdHTTP.Get() 将图像下载到您的TMemoryStream 后,您需要先将流搜索到位置 0,然后再对它进行任何操作,例如将其加载到您的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;
    

    【讨论】:

    • 仍然没有图像,只有空项目!,
    • 您没有为列表项分配任何文本。你如何显示他们的位图?你是如何配置列表框的?您是否调试过代码以确保位图不为空?
    • 我分配了 LBItem.Text := 'Test'; 并将其添加到 ListBox2 项目但没有图片!,我尝试了 LBItem.ItemData.Bitmap.SaveToFile('C:/1.jpg'); 并将图片保存在 C:/ !,我不明白为什么它没有显示在 ListBox2 项目 1
    • 你没有回答我的问题。您究竟是如何配置 ListBox 的?我自己不使用 FireMonkey,所以我不确定是否需要额外的步骤来告诉它如何显示ItemData.Bitmap。例如,您的 ListBox 的布局/样式是否定义了显示图像的位置,是否绑定到 ItemData.Bitmap
    • 老实说我不确定,但是 ListBox 中有 Images 属性 TCustomImageList,但是,我查看了 embarcadero 的 CustomListbox 示例,他们像这样使用它Item.ItemData.Bitmap := Image1.Bitmap
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多