listviewdelphibitmap

Adding image to listview in Delphi not showing


I have a listview in a Multi-device form using Delphi 12. I'm trying to add a image, but the image is not showing just a blank space. I don't know if it's the way I download the Image or do I have to convert it? I spend the whole day trying everything, look at all examples, but all of them had the images in a table or in a imagelist. I know I'm loading the Image twice since I want to check for nil.

Here is the code:

var
jsa: TJSONArray;
jso : TJsonObject;
i: Integer;
Name: String;
LItem: TListViewItem;
begin

if Length(S) > 10 then
   begin
      jso := TJSonObject.ParseJSONValue(S) as TJsonObject;
      if jso <> nil then
         Try
            jsa := jso.GetValue('results') as TJSONArray;
            if Jsa.Count > 0 then
               begin
                  for I := 0 to jsa.Count-1 do
                     begin                             
                         LItem := ListView1.Items.Add;
                         if GetImageFromURL(jsa[i].GetValue<string>('image')) <> nil then
                            LItem.Bitmap := GetImageFromURL(jsa[i].GetValue<string>('image'));
                         LItem.Detail := jsa[i].GetValue<string>('text');
                         LItem.Text := jsa[i].GetValue<string>('expire');
                     end;
               end;
        Finally
             jso.Free;
        End;

   end;

Here is the function that gets the image from a webserver.

function TPromoForm.GetImageFromURL(const S: String): TBitmap;
var
   ms       : TMemoryStream;
   httpCli  : TNetHTTPClient;
   resp     : IHTTPResponse;
   url      : String;
   Image: TBitmap;
begin
result := nil;
httpCli := TNetHTTPClient.Create(nil);
try
    httpCli.UserAgent := 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0';
    ms := TMemoryStream.Create();
    Image  := TBitmap.Create;
    Image := nil;
    try
        url  := S;
        resp := httpCli.Get(url, ms);
        if resp.StatusCode <> 200 then
           Showmessage(Format('HTTP Error=%d %s', [resp.StatusCode, resp.StatusText]))
        else
          begin
            try
              Image  := TBitmap.Create;
              ms.Position := 0;
              Image.LoadFromStream(ms);
              result := Image;
            finally
              Image.Free;
            end;
          end;
    finally
        ms.Free;
    end;
finally
    httpCli.Free;
end;
end;

The image is a jpg. Thanks for any help. Kim


Solution

  • You are Free'ing the TBitmap object before you exit from GetImageFromURL(), thus you are assigning an invalid object to the TListViewItem.Bitmap.

    You need to either: